Sub topic 14
Cow<str>: borrow when you can, own when you must
This chapter assumes you know ownership and borrowing, the difference between &str and String, and how Option and Result work. Here you will learn how Cow<str> lets a function return borrowed text when it changed nothing, and owned text only when it did.
The problem: sometimes you edit, sometimes you don't
Suppose a function replaces spaces with underscores. If the input has no spaces, the output equals the input. Returning String forces an allocation on every call, even when nothing changed. Returning &str is impossible when you did change something, because the new text has no owner to borrow from.
Cow solves this. The name stands for "clone on write". Cow<'a, str> is an enum with two variants:
Cow::Borrowed(&'a str)holds a reference to existing text.Cow::Owned(String)holds a heap-allocatedStringthat theCowowns.
A first example
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
fn main() {
for text in ["no_spaces", "has some spaces"] {
let result = normalize(text);
let kind = match &result {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
};
println!("{result} ({kind})");
}
}The first call prints no_spaces (borrowed) and allocates nothing. The second prints has_some_spaces (owned) and allocates one new String. The lifetime '_ ties the borrowed case to the input, so the result cannot outlive input.
Using a Cow
A Cow<str> implements Deref<Target = str>. You can call len, contains, split and other str methods on it directly, and you can pass &cow where &str is expected. Printing with {} also works, as the example shows.
Three methods cover most other needs:
into_owned()returns aString. It clones only if the value isBorrowed.to_mut()returns&mut String. If the value isBorrowed, it first clones the text into anOwnedvariant.to_string()always produces a newString.
The "write" in clone on write is to_mut:
use std::borrow::Cow;
fn ensure_exclaim(s: &str) -> Cow<'_, str> {
let mut cow = Cow::Borrowed(s);
if !s.ends_with('!') {
cow.to_mut().push('!');
}
cow
}
fn main() {
println!("{}", ensure_exclaim("hey!"));
println!("{}", ensure_exclaim("hey"));
}The clone happens only on the path that edits the text. Inputs that already end in ! pass through untouched.
When to use it
Cow<str> fits when most inputs need no change and the function is called often. Standard library examples include String::from_utf8_lossy, which returns a borrowed slice when the bytes are already valid UTF-8.
It is a poor fit when the output is nearly always modified, because you pay for the enum and the branches without saving allocations. For simple code that is not performance-sensitive, plain String is easier to read.
Common errors
- Forgetting the lifetime. A signature like
fn f(s: &str) -> Cow<str>compiles, butCow<'_, str>states the borrow explicitly and avoids lint warnings. - Calling
to_mutwhen you only need to read. It clones a borrowed value immediately. Read throughDerefinstead. - Returning a borrow of a local
String. If you build aStringinside the function and wrap a reference to it inBorrowed, the borrow checker rejects it. Wrap theStringitself inOwned.
Exercise
Write a function strip_tabs(input: &str) -> Cow<'_, str> that removes every tab character. It must not allocate when the input contains no tab. How do you check which case happened?
Show answer
Check input.contains('\t'). If true, return Cow::Owned(input.replace('\t', "")). Otherwise return Cow::Borrowed(input). To see which case happened, match on the result for Cow::Borrowed(_) or Cow::Owned(_), or use matches!(result, Cow::Borrowed(_)).