Cow in Rust

In Rust, the term "Cow" stands for "Clone on Write." It is a smart pointer that provides a flexible way to handle data that can be either borrowed or owned. This is particularly useful in scenarios where you want to avoid unnecessary data cloning, thus optimizing performance by cloning data only when it is necessary to modify it. The Cow type is an enum with two variants: Borrowed and Owned, and it is generic over a lifetime and a type that must implement the ToOwned trait.

Definition and Type Signature

The Cow type is defined in Rust's standard library as follows:

pub enum Cow<'a, B>
where
    B: 'a + ToOwned + ?Sized,
{
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}
  • Borrowed(&'a B) represents a borrowed variant, where B is a reference to the data.
  • Owned(<B as ToOwned>::Owned) represents an owned variant, where the data is owned and can be modified.

The Cow type allows you to work with data that might not need to be cloned unless a write operation is necessary. This is achieved through the ToOwned trait, which provides a way to convert a borrowed type into an owned type.

Basic Use of Cow

The Cow type can be used to handle data that is mostly immutable but needs to be mutated in certain situations. Here is an example demonstrating the 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
        .clone()
        .to_mut()
        .replace("moo", "toot");
dbg!(&cow_say_what);
dbg!(&cows_dont_say_what);

In this example, the original data remains immutable, and only the cloned data is mutated.

Practical Example

Consider a function generate_message() that generates messages, which are usually a &'static str. However, when an error occurs, additional information can be added using a struct called ErrorInfo.

use std::borrow::Cow;

#[derive(Debug)]
struct ErrorInfo {
    error: LocalError,
    message: String,
}

#[derive(Debug)]
enum LocalError {
    TooBig,
    TooSmall,
}

fn generate_message(
    message: &'static str, 
    error_info: Option<ErrorInfo>
) -> Cow<'static, str> {
    match error_info {
        None => message.into(),
        Some(info) => format!("{message}: {info:?}").into(),
    }
}

fn main() {
    let msg1 = generate_message(
        "Everything is fine",
        None
    );
    let msg2 = generate_message(
        "Got an error",
        Some(ErrorInfo {
            error: LocalError::TooBig,
            message: "It was too big".to_string(),
        }),
    );

    for msg in [msg1, msg2] {
        match msg {
            Cow::Borrowed(msg) => {
                println!("Borrowed, didn't need an allocation:\n  {msg}")
            }
            Cow::Owned(msg) => {
                println!("Owned, because we needed an allocation:\n  {msg}")
            }
        }
    }
}

In this example, if only a &'static str is passed without extra info, no allocation is needed, and the Cow will be a Cow::Borrowed. However, if extra info is required, an allocation is necessary, resulting in a Cow::Owned.

Using Cow in Structs

Cow can also be used in structs to handle both &str and String without unnecessary cloning. Consider a User struct that can take either &str or String:

use std::borrow::Cow;

struct User {
    name: Cow<'static, str>,
}

fn main() {
    let user_name = "User1";
    let other_user_name = "User10".to_string();

    let user1 = User {
        name: user_name.into(),
    };

    let user2 = User {
        name: other_user_name.into(),
    };

    for name in [user1.name, user2.name] {
        match name {
            Cow::Borrowed(n) => {
                println!("Borrowed name, didn't need an allocation:\n  {n}")
            }
            Cow::Owned(n) => {
                println!("Owned name because we needed an allocation:\n  {n}")
            }
        }
    }
}

In this scenario, both borrowed and owned values work seamlessly, allowing for efficient memory usage and flexibility in handling string data.

Considerations

While Cow provides a powerful mechanism for managing data efficiently, it is important to note that it does not inherently allocate data on the heap. If heap allocation is desired, you may need to use a Box within Cow, or consider using Rc or Arc for reference counting. Additionally, the clone-on-write feature is not a built-in language feature; it requires explicit use of the Cow trait to achieve the desired behavior.

| Book Title | Usage of cow | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|--------------|-----------------|-------------------------------|---------------|-----------------------|
| [Idiomatic Rust](https://www.manning.com/books/idiomatic-rust) | Discusses `Cow` as a smart pointer for efficient data handling, focusing on immutability and mutation of cloned data. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-9/76) | Detailed explanation of `Cow`'s enum variants and traits like `ToOwned` and `Deref`. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-9/78) | Connects `Cow` to concepts like lifetimes and smart pointers. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-9/78) | Provides examples of basic and improved use of `Cow`, including encapsulation in structs. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-9/76) | Shows practical use in functions and struct encapsulation to avoid exposing `Cow` in APIs. [more](https://livebook.manning.com/book/idiomatic-rust/chapter-9/78) |
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Introduces `Cow` as a flexible enum for handling borrowed and owned data, avoiding unnecessary allocations. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-11/56) | Simplified explanation of `Cow`'s signature and its use in avoiding allocations. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-11/56) | Highlights `Cow`'s role in memory management and efficient data handling. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-11/56) | Demonstrates `Cow` in functions and structs, showing how it handles `&str` and `String`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-11/56) | Practical examples include message generation and user struct handling with `Cow`. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-11/56) |
| [Code Like a Pro in Rust](https://www.manning.com/books/code-like-a-pro-in-rust) | Describes `Cow` as a smart pointer for handling borrowed or owned data, optimizing performance by cloning only when necessary. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-5/99) | Explains `Cow`'s enum definition and its use with the `ToOwned` trait. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-5/99) | Discusses `Cow` in the context of data structures like singly linked lists. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-5/99) | Provides a code example using `Cow` in a singly linked list to demonstrate immutability and cloning. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-5/99) | Highlights considerations for using `Cow`, such as heap allocation and reference counting. [more](https://livebook.manning.com/book/code-like-a-pro-in-rust/chapter-5/99) |

FAQ (Frequently asked questions)

What does Cow stand for in Rust?

What does 'Cow' stand for in Rust?

What are the variants of the Cow enum in Rust?

What trait must the type used with Cow implement?