RRust By Example

Cow (Clone on Write)

Lazy cloning with Cow for performance optimization.

Cow (Clone on Write)

Lazy cloning with Cow for performance optimization.

Difficulty

Advanced

Code

rust
use std::borrow::Cow;

fn ensure_owned(s: Cow<str>) -> String {
    // only clones if borrowed
    s.into_owned()
}

fn process(input: &str) -> Cow<str> {
    if input.contains("bad") {
        Cow::Owned(input.replace("bad", "good"))
    } else {
        Cow::Borrowed(input)
    }
}

fn main() {
    // borrowed case: no allocation
    let s1 = process("hello world");
    println!("{:?}", s1);

    // owned case: new allocation
    let s2 = process("bad word");
    println!("{:?}", s2);

    // Cow with Vec
    let v = vec![1, 2, 3];
    let cow: Cow<[i32]> = Cow::Borrowed(&v);
    println!("borrowed: {:?}", cow);
}

Explanation

Cow avoids cloning until mutation is needed.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the smart-pointers category to build a complete understanding of this topic.

More Smart Pointers Examples