skip to content

Cow and Clone-on-Write

Cow<'a, T> holds either a borrow or an owned value and clones only when you mutate. Interviewers ask when an API should return Cow<str> instead of String.

on this pageshow

questions

5

In Rust, what does a `std::borrow::Cow<'a, str>` hold, and how do you read its text or turn it into a `String`?

level: juniorimportance: should knowfreq 35%

answer

  1. one enum, two variants
  2. a borrow or an owned value
  3. Deref to the borrowed type
  4. into_owned clones only the borrowed case

basics

~10 s

A 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 lines
rust
use 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

for a junior

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.

for a middle

Explain that reading goes through Deref while mutation needs to_mut, because Cow has no DerefMut, and state exactly when into_owned allocates.

for a senior

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.

for a principal

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.
open as a page

When should a Rust function return `Cow<'a, str>` instead of `String`, for example a sanitiser that rarely needs to escape anything?

level: middleimportance: should knowfreq 35%

basics

~20 s

Return Cow<'a, str> when a function takes a &str and usually returns it unchanged: the common path returns Cow::Borrowed(input) with no allocation, and only the rare path that changes the text builds a String and returns Cow::Owned.

open as a page

In Rust, what does `Cow::to_mut` do on a `Cow::Borrowed` versus a `Cow::Owned`, and how does it differ from `into_owned`?

level: middleimportance: should knowfreq 25%

basics

~20 s

Cow::to_mut takes &mut self and returns a mutable reference to the owned value: on Borrowed it clones the data once and switches the Cow to Owned, on Owned it clones nothing. into_owned consumes the Cow and returns the owned value, cloning only if Borrowed.

open as a page

A Rust struct with a `Cow<'a, str>` field is deserialized with serde_json; why is the field always `Cow::Owned`, and when can it borrow instead?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

serde's Deserialize impl for Cow<'a, T> always deserializes T::Owned and wraps it in Cow::Owned. With #[serde(borrow)] on the field, serde_json::from_str yields Cow::Borrowed for strings without escapes and Cow::Owned when it must unescape.

open as a page

Why does `Cow<'_, [Token]>` fail with E0277 when `Token` is not `Clone`, and why do Rust APIs write `Cow<str>` rather than `Cow<String>`?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Cow<'a, B> requires B: ToOwned, and std implements ToOwned for [T] only when T: Clone, so naming Cow<[Token]> fails with E0277 even if nothing is ever cloned. B is the borrowed form: str, whose owned type is String.

open as a page