Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 132 ยท Smart Pointers and Memory

Cow, Borrow and Avoiding Clones

Learn when Rust code really needs to allocate. Cow<str>, ToOwned, Borrow, AsRef, choosing &str over String in APIs, and zero-copy parsing with slices.

New Rust programmers often fix borrow checker errors by sprinkling .clone() and .to_string() everywhere. It works, and for a small program it is fine. But every clone of a String or Vec is a heap allocation plus a copy, and in code that handles millions of items those costs add up. Rust gives you a family of tools to allocate only when you must: choosing the right parameter types, the Cow ("clone on write") enum, the Borrow and AsRef traits, and parsing by slicing the input instead of copying it.

This lesson teaches each tool by showing the problem it solves. It assumes you know ownership, borrowing and slices, and the difference between String and &str from Strings. It pairs with Memory Layout and Sizes, which shows what an allocation actually is.

The cost you are avoiding

A String owns a heap buffer. Cloning it asks the allocator for new memory and copies every byte. A &str is just a pointer and a length (16 bytes) into memory someone else owns: copying a &str copies those 16 bytes, no matter how long the text is.

Rust A clone copies the data, a borrow does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

(Comparing pointers is fine for a demonstration like this. We only print true or false, never the addresses.) The goal of the rest of the lesson is to make as many values as possible look like borrowed instead of cloned.

Take &str and &[T] in parameters

The cheapest win needs no new feature: accept borrowed slices instead of owned containers.

Rust Why &str parameters are more flexible

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A function that takes &str works with String, &String, string literals and substrings. A function that takes &Vec<i32> works only with vectors; &[i32] works with vectors, arrays and sub-slices. Clippy warns about &String and &Vec<T> parameters (the ptr_arg lint) for exactly this reason.

Take ownership (String, Vec<T>) only when the function will store the value or consume it. When a function needs to keep a copy, let the caller decide whether to move or clone:

Rust
struct User {
    name: String,
}

impl User {
    // Caller moves a String in, or writes .to_string() when it only has a &str.
    fn new(name: String) -> User {
        User { name }
    }

    // Flexible: accepts &str, String, &String, Box<str>, char...
    fn named(name: impl Into<String>) -> User {
        User { name: name.into() }
    }
}

impl Into<String> accepts anything convertible to a String, and passing an owned String into it does not copy. The cost is that the function is generic (one compiled copy per argument type), so use it for constructors and setters, not hot inner loops.

The problem Cow solves

Sometimes a function usually returns its input unchanged but occasionally has to build something new. Think of "remove tabs", "escape HTML", or "normalize the path". If it returns String, it must allocate on every call, even for the 99% of inputs that need no change. If it returns &str, it cannot return a modified version at all.

Cow ("clone on write") has two variants and fits in between:

Rust
// Simplified definition from the standard library
enum Cow<'a, B: ?Sized + ToOwned> {
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}

For text, Cow<'a, str> is either Borrowed(&str) or Owned(String). It dereferences to &str, so most code can use it like a string without caring which variant it holds.

Rust Allocate only when something changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The return type Cow<'_, str> is honest about what the function does: "I give you text that is borrowed from the input or freshly owned." Callers use .len(), .contains(), println! and every other &str method directly. When they need a real String, they call .into_owned(), which moves the buffer out for free if the value is already Owned and copies only if it is Borrowed.

The standard library uses this idea itself. String::from_utf8_lossy(bytes) returns Cow<str>: borrowed when the bytes are valid UTF-8 (the common case), owned when invalid bytes had to be replaced with the replacement character.

Rust from_utf8_lossy returns a Cow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Cow::to_mut: clone only when you write

to_mut() gives you &mut String. If the Cow is borrowed, it clones the data into a new String first (once); if already owned, it just hands you the existing one. That is the "write" in clone-on-write.

Rust to_mut clones lazily

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Cow is not limited to strings. Cow<'a, [T]> works for slices (with Vec<T> as the owned form), and Cow<'a, Path> for paths. A struct can hold Cow<'a, str> fields so it can be built cheaply from literals ('static borrowed) and still accept runtime-built strings.

Use Cow when a function often has nothing to change. If it always allocates anyway, return a String; if it never allocates, return &str. Cow adds a tag and a little branching, which is worth it only when the saved allocations are real.

ToOwned: the general version of clone

.to_owned() turns a borrowed value into an owned one, and unlike .clone() it can change the type. Calling .clone() on a &str would only copy the reference (the compiler even warns that it does nothing); ToOwned on a str produces a String.

Rust to_owned changes the type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

ToOwned is what powers Cow: it describes, for an unsized type like str or [T], which sized type owns it (String, Vec<T>).

Borrow and AsRef: flexible lookups and parameters

Two small traits turn up all over the standard library, and they look alike but have different jobs.

Borrow: "I can be viewed as that, with the same equality and hash"

HashMap<String, V> stores owned strings, but you can look up with a &str and avoid creating a temporary String. The magic is Borrow<str>: String implements it, and get accepts any Q where the key type implements Borrow<Q>.

Rust Looking up a String key with a &str

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Borrow comes with a contract: the borrowed form must hash and compare exactly like the owned form. That is why String borrows as str but not as, say, a lowercased copy. Implement Borrow yourself only if that contract really holds.

AsRef: "I can give you a cheap reference to that"

AsRef<T> is a plain conversion with no equality promise. Use it for parameters so callers can pass whichever type they have. The standard library's file functions are the best example: they take impl AsRef<Path>, so &str, String, &Path and PathBuf all work.

Rust AsRef in your own functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A rule of thumb for parameters:

You want to... Use
Read text only &str
Accept several string-like types at the API boundary impl AsRef<str>
Store a String and let callers pass &str or String impl Into<String>
Accept file paths impl AsRef<Path>
Look something up in a collection borrowed key type, relying on Borrow

AsRef and Into make a function generic, so the compiler builds a copy per type. A common trick is to keep the generic function thin and call a private non-generic function that does the real work.

Zero-copy parsing

The biggest saving is in parsing. If you split a big text into pieces and store each piece as a String, you copy the entire input. If you store &str slices that point into the original, you copy nothing: the pieces are just (pointer, length) pairs. The price is a lifetime: the result may not outlive the input.

Rust Parsing log lines into borrowed slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Entry<'a> holds references with lifetime 'a, tied by the signature parse_line(&str) -> Option<Entry<'_>> to the input. If the input String is dropped while entries still exist, the compiler stops you:

Rust Borrowed parse results cannot outlive the input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0597]: `line` does not live long enough

The fix is one of: keep the input alive longer, or convert to owned data (word.to_owned()) at the point where you need independence. Libraries such as serde_json offer the same choice: deserialize into &str fields (zero-copy, tied to the input buffer) or String fields (owned, free-standing). A Cow<'a, str> field is the middle path: borrowed when possible, owned when the text had to be modified, for example when a JSON string contains escape sequences.

When to clone anyway

Avoiding clones is a means, not a goal. Cloning is the right choice when:

  • the data is small (a few bytes, an Rc, or an integer-sized handle);
  • you need the data to outlive its source and a lifetime parameter would infect your whole API;
  • the code is not on a hot path, and clarity matters more than a saved allocation;
  • profiling shows allocations are not your bottleneck.

Before optimizing, measure (see the lesson on Performance). The pattern to watch for is a clone inside a loop, or a clone made only to satisfy the borrow checker when restructuring the code would solve it. See Lifetime Patterns and Pitfalls for ways to restructure.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which parameter type is the most flexible for a function that only reads text?

    &str accepts a &String (by deref coercion), string literals and substrings. String forces the caller to give up or clone their value, and &String works only with owned strings.
  2. 2. What does Cow::Borrowed mean?

    Borrowed wraps a reference. Only when you call to_mut() (or into_owned()) does the Cow clone the data into an Owned value.
  3. 3. Why can you call map.get("apples") on a HashMap<String, u32>?

    get is generic over a borrowed key type Q where K: Borrow<Q>. String implements Borrow<str> with the same hash and equality as str, so no temporary String is needed.
  4. 4. A function returns Cow<str> and is called with text that needs no change. What does it return?

    That is the point of Cow: the unchanged fast path returns a borrow of the input, and only inputs that need modification allocate a new String.
  5. 5. What is the main cost of zero-copy parsing into a struct with &'a str fields?

    The fields point into the original input, so the compiler ties the struct's lifetime to it. If you need independence, convert the fields to owned Strings.

Summary

  • Cloning a String or Vec allocates and copies; borrowing a &str or &[T] copies only a pointer and a length.
  • Take &str and &[T] in parameters unless the function must store or consume the value.
  • Cow<'a, str> returns borrowed data on the fast path and an owned String only when something changed; to_mut() clones lazily and into_owned() extracts a String.
  • ToOwned generalizes clone for unsized types (str becomes String, [T] becomes Vec<T>).
  • Borrow (same hash and equality) powers lookups like map.get("key"); AsRef and Into<String> make parameters accept many types.
  • Zero-copy parsing keeps slices of the input, at the price of a lifetime.
  • Clone freely when data is small, off the hot path, or when a lifetime would complicate your API.

Next: Unsafe Rust