Cow and clone-on-write
Quick answer
Cow<'a, B> holds either borrowed data or an owned form of that data. Use it when most inputs can be returned unchanged but some require an allocated transformation.
Borrow first, own on demand
For Cow<'_, str>, the borrowed form is &str and the owned form is String. to_mut returns mutable access to the owned form, cloning if needed. into_owned consumes the Cow and obtains an owned value. The lifetime still matters when a borrowed variant is possible.
use std::borrow::Cow;fn label(s: &str) -> Cow<'_, str> { if s.contains('_') { Cow::Owned(s.replace('_', " ")) } else { Cow::Borrowed(s) } }fn main() { let a = label("red"); let b = label("red_blue"); println!("borrowed: {}, changed: {}", matches!(a, Cow::Borrowed(_)), b); }Expected stdout (not executed):
borrowed: true, changed: red blueThe unchanged string can remain borrowed.
use std::borrow::Cow;fn main() { let original = String::from("hi"); let mut view: Cow<'_, str> = Cow::Borrowed(&original); view.to_mut().push('!'); println!("{original} / {view}"); }Expected stdout (not executed):
hi / hi!Mutation affects an owned copy, not the original.
Common mistake
Cow does not guarantee that cloning is avoided; mutation or forced ownership may require copying.
Try it yourself
Return a borrowed label when no uppercase letters exist, otherwise an owned lowercase label.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cow and clone-on-write — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Most labels need no normalization; a few need replacement. Which return type can avoid copies for unchanged labels?
Cow and clone-on-write — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::borrow::Cow; fn label(s: &str) -> Cow<'_, str> { if s.contains('_') { Cow::Owned(s.replace('_', " ")) } else { Cow::Borrowed(s) } } fn main() { let a = label("red"); let b = label("red_blue"); println!("borrowed: {}, changed: {}", matches!(a, Cow::Borrowed(_)), b); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Cow and clone-on-write — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::borrow::Cow; fn main() { let original = String::from("hi"); let mut view: Cow<'_, str> = Cow::Borrowed(&original); view.to_mut().push('!'); println!("{original} / {view}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.