`Cow`
Cow<B> is clone-on-write: either a borrow of B or an owned B::Owned. You clone only when a mutation or an API requires ownership.
Detailed Explanation
Cow stands for clone-on-write. Cow<'a, str> is either Cow::Borrowed(&'a str) or Cow::Owned(String). Cow<'a, [T]> is a borrowed slice or a Vec<T>. The type implements Deref to the borrowed form, so a Cow<str> prints and indexes like a &str.
You reach for it when a function sometimes returns data it already has and sometimes must allocate. fn name(&self) -> Cow<'_, str> can return a borrowed field when the name is already clean, and an owned String when it has to replace characters. Callers can treat the result as &str. Callers that need a String call .into_owned(), which clones only in the borrowed arm.
to_mut is the write path. On a borrowed Cow it clones into the owned form and returns &mut Owned. On an owned Cow it returns &mut Owned without cloning. That is the "clone on write": the clone happens at the first mutation, not at construction.
Cow is not a garbage collector and not a shared pointer. Two Cow::Borrowed values can point at the same data because they are borrows. Two Cow::Owned values do not share. There is no reference count.
The cost is the enum tag and the extra match in to_mut. For an API that almost always borrows, Cow saves allocations at the call sites that used to .to_string() "just in case". For an API that almost always owns, a String is simpler.
When you return Cow: a getter that is usually a borrow and sometimes a computed string. When you take impl Into<Cow<'a, str>>: you want to accept both &str and String and delay the clone. When both sides always own, skip Cow.
Code Examples
use std::borrow::Cow;
fn label(name: &str) -> Cow<'_, str> {
if name.is_empty() {
Cow::Borrowed("guest")
} else {
Cow::Borrowed(name)
}
}
fn main() {
println!("{}", label("ada")); // prints: ada
println!("{}", label("")); // prints: guest
let owned = label("ada").into_owned();
println!("{owned}"); // prints: ada
}Common Gotchas
`into_owned` clones only when borrowed
An already-owned `Cow` moves the `String` out. That is the cheap arm.
`to_mut` on a big borrowed buffer clones the whole buffer
The first write pays. If you know you will mutate, start with `Cow::Owned`.
`Cow<str>` derefs to `str`, not `String`
String methods that need `&mut String` require `to_mut`.
Do not use `Cow` to hide a lifetime problem
If the data must outlive the source, you need ownership up front, not a borrowed `Cow`.