liveBook · Manning

Cow

As explained in Learn Rust in a Month of Lunches

Cow is a Rust standard-library clone-on-write enum that can represent either borrowed data or owned data and create an owned copy when necessary.

Cow means “clone on write.” It can hold either borrowed data or an owned value, so code can avoid creating an owned copy until it needs one. section 11.4

enum Cow<'a, B>
where
    B: 'a + ToOwned + ?Sized,
 {
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}

The full signature shows the lifetime, the borrowed type B, the ToOwned requirement, and the Borrowed and Owned variants. section 11.4

The two variants represent different storage choices:

  • Borrowed holds a reference such as &'static str when the existing data is enough. section 11.4
  • Owned holds the owned form, such as String, when producing or modifying the value requires ownership. section 11.4
  • into_owned and into_borrowed provide ways to change the representation when needed. section 11.4

Returning a message

A message function can return Cow<'static, str>. With no error, message.into() produces a borrowed value. With error details, format!("{message}: {info:?}").into() produces an owned String. Matching on Cow::Borrowed and Cow::Owned lets the program report which choice it made.

Storing user names

A User with name: Cow<'static, str> can hold either a string literal or an owned String. The borrowed User1 avoids an allocation, while the owned User10 keeps its allocated value.

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains variants, generics, lifetimes, ToOwned, dynamically sized types, matching, and conversion methods.
Examples
Uses conditional message generation and User names to contrast borrowed values with allocated owned values.
What it assumes
Assumes familiarity with references, ownership, lifetimes, generics, enums, and dynamically sized types.
What you can do after
Apply it via std::borrow::Cow to accept, return, or store borrowed and owned data in one type.
How it connects
Connects ownership with lifetimes, borrowing, ToOwned, String, format!, and dynamically sized types.

Also explained in

Compare how 2 books explain Cow →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.