liveBook · Manning

Cow

As explained in Idiomatic Rust

Cow is Rust's standard-library copy-on-write smart pointer that can represent either borrowed data or owned data.

Cow is a clone-on-write smart pointer for data that should remain borrowed unless mutation is needed. It stores either Borrowed or Owned data, requires ToOwned, and dereferences to its contents. Calling to_mut() provides mutable access, cloning into owned data when necessary so changes do not alter the source. section 9.7

Listing 9.6 Basic use of Cow
use std::borrow::Cow;

let cow_say_what = Cow::from("The cow goes moo");
dbg!(&cow_say_what);

let cows_dont_say_what =
    cow_say_what                     #1
        .clone()                     #1
        .to_mut()                    #1
        .replace("moo", "toot");     #1
dbg!(&cow_say_what);             #2
dbg!(&cows_dont_say_what);   #3

This example clones the Cow pointer, then replaces “moo” through to_mut(); the original value remains unchanged. section 9.7

A transformation can accept and return Cow, mutating only when needed. For a public API, wrap Cow in a struct and expose methods rather than the implementation detail; a Cow-backed list can add items while preserving earlier values. section 9.7

How Idiomatic Rust covers it

How deep it goes
Defines Borrowed and Owned variants, ToOwned bounds, Deref, and to_mut cloning without detailing implementation internals.
Examples
Demonstrates string replacement, a conditional loud_moo transformation, and a Cow-backed list that preserves earlier values.
What it assumes
Builds on Clone and ToOwned, explaining ToOwned as a generalization of cloning for references or slices.
What you can do after
Apply it via Rust’s standard library to mutate a Cow-backed value while leaving the source unchanged.
How it connects
Ties Cow to ToOwned, Clone, Deref, and immutable-data patterns.

Also explained in

Compare how 2 books explain Cow →

Related concepts

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