How to Use Cow<T> (Clone on Write) in Rust

Use std::borrow::Cow to hold borrowed or owned data, cloning only when mutation occurs.

Rust does not have a built-in Cow<T> type for Clone-on-Write; you must use the standard library's std::borrow::Cow to achieve this pattern. Import Cow and use Cow::Borrowed for read-only access or Cow::Owned when you need to modify the data, letting the compiler handle the clone automatically if you mutate a borrowed value.

use std::borrow::Cow;

fn main() {
    let mut s: Cow<str> = Cow::Borrowed("hello");
    s.to_mut(); // Clones to owned if needed
    s.push_str(" world");
    println!("{s}");
}