skip to content

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%

answer

  1. the common path changes nothing
  2. borrow the input, allocate rarely
  3. result tied to the input's lifetime
  4. owned input, owned output

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.

solid answer

~40 s

A sanitiser such as `fn escape_html(input: &str) -> String` allocates on every call, even when the input contains nothing to escape. Written as `fn escape_html(input: &str) -> Cow<'_, str>`, it scans first and returns `Cow::Borrowed(input)` when nothing needs changing; only the rare dirty input pays for a new `String`, returned as `Cow::Owned`. Elision ties the result's lifetime to `input`, so a caller who just prints or compares the result pays nothing, and one who must store it calls `into_owned()` and pays at most one copy. Return `String` instead when most inputs change anyway, or when the function takes an owned `String` and can hand back the same buffer: std draws the same line, with `String::from_utf8_lossy(&[u8]) -> Cow<'_, str>` and, since Rust 1.99, `String::from_utf8_lossy_owned(Vec<u8>) -> String`.

code

rust · 29 lines
rust
use std::borrow::Cow;

fn escape_html(input: &str) -> Cow<'_, str> {
    if !input.contains(['<', '>', '&', '"']) {
        return Cow::Borrowed(input);
    }
    let mut out = String::with_capacity(input.len() + 8);
    for c in input.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    Cow::Owned(out)
}

fn main() {
    for s in ["plain text", "a < b && c"] {
        let clean = escape_html(s);
        let kind = match &clean {
            Cow::Borrowed(_) => "borrowed",
            Cow::Owned(_) => "owned",
        };
        println!("{kind}: {clean} ({} bytes)", clean.len());
    }
}

go deeper

for a junior

Recall that a function can return the input as Cow::Borrowed when nothing changes and a new String as Cow::Owned when something does.

for a middle

Explain how lifetime elision ties the returned Cow to the input, why the scan must come before any allocation, and when into_owned costs a copy.

for a senior

Judge when Cow pays off: borrowed input that is usually unchanged. Recommend String when most inputs change or the input is owned, and cite from_utf8_lossy beside from_utf8_lossy_owned.

for a principal

Weigh the API cost: a Cow return puts a lifetime in every caller's code, so reserve it for measured hot paths and keep owned types at storage boundaries.

## The cost a `String` return hides Many text functions are **usually identity functions**: an HTML escaper sees `<` or `&` in a small fraction of inputs, a path normaliser rarely meets `..`, a trimmer often finds nothing to trim. If such a function returns `String`, it must allocate and copy on every call, because a `String` always owns its buffer. On a hot path (a template engine, a log formatter, a request router) that is one heap allocation per call for no change at all. `std::borrow::Cow<'a, str>` removes that cost. It is an enum of `Cow::Borrowed(&'a str)` and `Cow::Owned(String)`, so one return type can mean "here is your input back" or "here is a new string". ## The `Cow` signature ```rust fn escape_html(input: &str) -> Cow<'_, str> ``` - **`'_` is the elided lifetime**: with one reference parameter, the output borrows from `input`. Spelled out, it is `fn escape_html<'a>(input: &'a str) -> Cow<'a, str>`. - **The common path** does a cheap scan, such as `input.contains(['<', '>', '&', '"'])`, and returns `Cow::Borrowed(input)`: no allocation, no copy. - **The rare path** builds a `String` (sized with `String::with_capacity` to avoid regrowth) and returns `Cow::Owned(out)`. The scan must come **before** any allocation. Building a `String` and comparing it with the input at the end would allocate on every call, which defeats the point. A refinement is to find the first byte that needs escaping, copy the clean prefix once, and continue from there. ## What the caller sees 1. **Reading** needs nothing special: `Cow<'_, str>` derefs to `str`, implements `Display`, and compares equal to `&str` and `String`. 2. **Storing** past the input's lifetime needs `into_owned()`, which returns the `String` from an `Owned` value with no copy, or copies a `Borrowed` one. 3. **Lifetimes** are the real cost. The result cannot outlive `input`. `let s = { let t = String::from("x"); escape_html(&t) };` fails with E0597, `t` does not live long enough, because the returned `Cow` may borrow `t`. ## A trace through two inputs Run the sanitiser from the code example on two strings: 1. `escape_html("plain text")`: the scan finds none of `<`, `>`, `&` or `"`, so the function returns `Cow::Borrowed` over the caller's bytes. `clean.len()` reads 10 through `Deref`, and printing it uses `Display`. No heap allocation happened anywhere. 2. `escape_html("a < b && c")`: the scan finds `<`, so the function allocates one `String` with spare capacity, pushes `&lt;` and `&amp;` in place of the special characters, and returns `Cow::Owned`. The result is 21 bytes. The caller's loop body is identical for both: it never needs to know which variant came back unless it wants to report it, which the example does with a `match` on `&clean`. That uniformity is what makes `Cow` cheap to adopt: existing code that reads a `&str` keeps compiling once it receives `&cow`. ## When not to return `Cow` | Input | Usual outcome | Best return type | |---|---|---| | `&str` | unchanged | `Cow<'_, str>` | | `&str` | almost always changed | `String` | | `String` by value | unchanged | `String`, the same buffer handed back | | `&str`, result kept in a long-lived struct | either | `String`, or `Cow` plus `into_owned` at the boundary | With an **owned input** there is nothing to borrow from: return `String` and give the caller back their own buffer when nothing changes. Returning `Cow<'static, str>` from a function that takes `String` only adds a branch. ## std's own pair The standard library draws this exact line for lossy UTF-8 decoding: - `String::from_utf8_lossy(v: &[u8]) -> Cow<'_, str>` returns `Cow::Borrowed` over the input when every byte is valid UTF-8 and builds a `String`, with `U+FFFD` in place of each invalid sequence, only when it must. - `String::from_utf8_lossy_owned(v: Vec<u8>) -> String`, **stable since Rust 1.99.0**, takes the bytes by value and returns a `String`. Its current implementation calls `from_utf8_lossy` and, when that borrowed, converts the original `Vec` in place; its documentation adds that reuse of the original allocation is not guaranteed. Before 1.99, the owned-input case was usually written as `String::from_utf8_lossy(&v).into_owned()`, which copies valid input into a second buffer. ## Review checklist - Does the function take a borrowed input and leave it unchanged most of the time? If not, return `String`. - Does the fast path return `Cow::Borrowed` before allocating anything? - Will callers keep the result beyond the input's lifetime? Then they call `into_owned()` once, at that boundary. - Is the signature honest? `Cow` in a public API tells every caller the result may borrow from the argument.

  • Why must the sanitiser scan before it allocates, rather than build a `String` and compare at the end?
    Building then comparing allocates on every call, which is exactly the cost `Cow` exists to avoid. A cheap scan decides the variant: no special characters means `Cow::Borrowed(input)`. A good implementation finds the first byte that needs escaping, copies the clean prefix once into a `String` sized with `with_capacity`, and continues from there, so the owned path does not rescan.
  • If the function takes a `String` by value, should it still return `Cow`?
    No. With an owned input there is nothing to borrow from, so return `String` and hand back the same buffer when nothing changes. std's `String::from_utf8_lossy_owned`, stable since Rust 1.99, takes a `Vec<u8>` and returns a `String`; its current implementation reuses the bytes' buffer when they are already valid, though its documentation does not guarantee that reuse.
  • What does returning `Cow<'_, str>` cost a caller compared with `String`?
    The result borrows the argument, so it cannot outlive it: keeping it in a struct or sending it to another thread needs `into_owned()` first. The signature carries a lifetime, and every deref branches on the variant. For callers that just format, compare or parse the result, none of that matters, and they skip an allocation on the common path.

  • Returning Cow<str> means the function never allocates.
  • Every caller must call into_owned before using the result.
  • A Cow<'_, str> result can outlive the &str it was built from.
  • Cow is worth returning even when almost every input gets modified.
  • Cow::Borrowed copies the input text into the Cow.

Assumes Rust 1.99; String::from_utf8_lossy_owned, the owned-input counterpart of from_utf8_lossy, is stable since 1.99.0.