In Rust, what does a `std::borrow::Cow<'a, str>` hold, and how do you read its text or turn it into a `String`?
answer
- one enum, two variants
- a borrow or an owned value
- Deref to the borrowed type
- into_owned clones only the borrowed case
basics
~10 sA Cow<'a, str> is an enum holding either Cow::Borrowed(&'a str) or Cow::Owned(String). It derefs to str, so you read it like a &str, and into_owned() returns a String, allocating only when it was borrowed.
solid answer
~40 s`Cow` (clone-on-write) is defined as `enum Cow<'a, B: ?Sized + 'a> where B: ToOwned { Borrowed(&'a B), Owned(<B as ToOwned>::Owned) }`, so a `Cow<'a, str>` is either a borrowed `&'a str` or an owned `String`. It implements `Deref<Target = str>`, so you call `len`, `trim` or `contains` on it directly and pass `&cow` wherever a `&str` is expected; it also implements `Display`, `Hash`, `Ord` and `PartialEq` against `str`, `&str` and `String`, all by the text. To own the text, `into_owned()` consumes the `Cow`: an `Owned` value is moved out with no copy, a `Borrowed` one is copied into a new `String`. You build one with `Cow::Borrowed(s)`, `Cow::Owned(string)` or `.into()` from a `&str` or a `String`, and std returns one from `String::from_utf8_lossy`, which borrows when the bytes are already valid UTF-8.
code
rust · 27 linesuse std::borrow::Cow;
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let good: &[u8] = b"hello";
let bad: &[u8] = b"hel\xFFlo";
let a: Cow<'_, str> = String::from_utf8_lossy(good);
let b: Cow<'_, str> = String::from_utf8_lossy(bad);
println!("{}", matches!(a, Cow::Borrowed(_))); // true: no allocation
println!("{}", matches!(b, Cow::Owned(_))); // true: U+FFFD inserted
// Deref to str: call &str methods and pass &Cow where &str is expected
println!("{} {}", a.len(), shout(&b));
// Into an owned String: allocates only for the Borrowed case
let owned: String = b.into_owned();
println!("{owned}");
let c: Cow<'static, str> = "literal".into(); // From<&str> -> Borrowed
let d: Cow<'static, str> = format!("n={}", 3).into(); // From<String> -> Owned
println!("{c} {d}");
}go deeper
Recall the two variants and that Cow<str> means either a &str or a String. Show that you can call &str methods on it and get a String with into_owned.
Explain that reading goes through Deref while mutation needs to_mut, because Cow has no DerefMut, and state exactly when into_owned allocates.
Point to std APIs such as String::from_utf8_lossy that return Cow so the common case allocates nothing, and say when a caller should keep the Cow instead of converting it.
Frame Cow as a signature-level promise about allocation: it tells every caller the result may borrow from the input, which shapes how long they can keep it.
## What a `Cow` is `std::borrow::Cow` is a **clone-on-write** smart pointer. It is a plain enum with two variants, defined in the `alloc` crate and re-exported from `std::borrow`: ```rust pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned, { Borrowed(&'a B), Owned(<B as ToOwned>::Owned), } ``` `B` is the **borrowed form** of the data. For text, `B` is `str`, and `str`'s owned counterpart (its `ToOwned::Owned` type) is `String`. So a `Cow<'a, str>` is one of two things: | Variant | Holds | Allocated by the `Cow`? | |---|---|---| | `Cow::Borrowed(&'a str)` | a reference to text someone else owns | no | | `Cow::Owned(String)` | its own heap buffer | yes, the `String` owns it | The lifetime `'a` only constrains the `Borrowed` case: as long as the `Cow` might hold a `&'a str`, it cannot outlive the data that reference points to. A `Cow<'static, str>` can hold either a string literal or an owned `String`. ## Reading the text: `Deref` `Cow<'_, B>` implements `Deref<Target = B>`. For `Cow<'_, str>` that means: - **Method calls auto-deref**: `cow.len()`, `cow.trim()`, `cow.starts_with("GET")` work without a `match`. - **Deref coercion**: `&cow` has type `&Cow<'_, str>` but coerces to `&str` at a call site that expects `&str`. - **Formatting and comparison**: `Cow<'_, str>` implements `Display` and `Debug` by delegating to the text, and `PartialEq` against `str`, `&str` and `String`, so `assert_eq!(cow, "hello")` compiles. - **Hashing and ordering** are by the text too, so a `Borrowed` and an `Owned` holding the same characters are equal and hash the same. What `Cow` does **not** implement is `DerefMut`. You cannot call `String` methods such as `push_str` through it: rustc reports E0599, "no method named `push_str` found for enum `Cow<'_, str>` in the current scope". Mutation goes through `Cow::to_mut`, which returns `&mut String` and copies the text first if the `Cow` was borrowed. ## Getting a `String` out `Cow::into_owned(self)` consumes the `Cow` and returns `<B as ToOwned>::Owned`, here a `String`: 1. On `Cow::Owned(s)` it returns `s` itself. The standard library's documentation states the data is moved out without being cloned. 2. On `Cow::Borrowed(r)` it calls `r.to_owned()`, which allocates a new `String` and copies the bytes. So `into_owned` costs at most one copy, and only when the `Cow` was borrowed. `String::from(cow)` and `cow.into()` with a `String` target do the same thing through the `From<Cow<'a, str>> for String` impl. ## Building one - `Cow::Borrowed("literal")` or `Cow::Owned(String::from("x"))` name the variant directly. - `From` impls choose it for you: a `&'a str` or a `&'a String` becomes `Borrowed`, a `String` becomes `Owned`. That is why `let c: Cow<'static, str> = "ready".into();` and `let c: Cow<'static, str> = format!("n={n}").into();` both compile. - A parameter typed `impl Into<Cow<'static, str>>` accepts both a literal and a `String`, so a constructor stores either without forcing callers to allocate. ## Storing one in a struct A `Cow<'static, str>` field is a common way to hold text that is **usually a literal but sometimes computed**, such as an error message or a display label: - `Problem { msg: "disk full".into() }` stores `Cow::Borrowed` over a `&'static str`, with no allocation. - `Problem { msg: format!("disk {n} full").into() }` stores `Cow::Owned(String)`. - Because the lifetime is `'static`, the struct carries no lifetime parameter and can be kept anywhere, including in another thread. A constructor written as `fn new(msg: impl Into<Cow<'static, str>>) -> Self` accepts both forms at the call site, so callers who pass a literal never pay for a `String` they do not need. With a non-`'static` lifetime, `Cow<'a, str>` fields make the struct itself generic over `'a`, which is the trade-off to weigh before reaching for it. ## Where std hands you one The most common place to meet a `Cow<'_, str>` is `String::from_utf8_lossy(v: &[u8])`. Its implementation walks the bytes; if they are all valid UTF-8 it returns `Cow::Borrowed` pointing into the input, and only if it finds an invalid sequence does it build a `String`, substituting `U+FFFD` for each bad sequence, and return `Cow::Owned`. `Path::to_string_lossy` and `OsStr::to_string_lossy` follow the same shape. ## Mistakes to avoid - **Matching before every read.** `Deref` makes the variant irrelevant for reading; match only when you care whether an allocation happened. - **Assuming `into_owned` always copies.** It moves an owned value out for free. - **Confusing `Cow` with reference counting.** `Cow` has no counter and no sharing: an `Owned` `Cow` is the only owner of its `String`. - **Calling the unstable inspectors.** `Cow::is_borrowed` and `Cow::is_owned` exist only behind the unstable `cow_is_borrowed` feature; on stable Rust write `matches!(cow, Cow::Borrowed(_))`.
- Why can't you call `push_str` on a `Cow<'_, str>` directly?`Cow` implements `Deref` but not `DerefMut`, and its deref target is `str`, which has no `push_str`. rustc reports E0599, no method named `push_str` found for enum `Cow<'_, str>`. To change the text you call `to_mut()`, which returns `&mut String`, copying the borrowed text into a new `String` first if the `Cow` was `Borrowed`.
- How do you tell, on stable Rust, whether a `Cow` you received allocated?Match on it: `matches!(cow, Cow::Borrowed(_))` is true when no `String` was built for it. `Cow::is_borrowed` and `Cow::is_owned` exist but are unstable behind the `cow_is_borrowed` feature, so stable code cannot call them. `Owned` means the producer built or handed over a `String`; it does not tell you how many allocations that took.
- Cow is a reference-counted pointer, like Rc, that shares one buffer.
- A Cow<str> always allocates a String up front.
- You must match on the variant before you can read the text.
- into_owned always copies, even when the Cow is already Owned.
- Cow implements DerefMut, so push_str works through it.