std-type
Rust Cow borrowed and owned values
Cow represents either borrowed data or an owned counterpart. Use it when an operation can frequently return its input unchanged, but must sometimes produce a new value. It is clone-on-write, not shared-reference mutation of the input. Expected output (not executed): true in stock Why: Unchanged input can be returned without making a new String. Common mistake: Promising zero allocations for every Cow operation.
Formal Syntax & Structure
rust syntaxrust
Cow<'a, str>Working Example
Example Snippetrust
use std::borrow::Cow;fn normalize(text: &str) -> Cow<'_, str> { if text.contains('_') { Cow::Owned(text.replace('_', " ")) } else { Cow::Borrowed(text) }}fn main() { println!("{}", matches!(normalize("ready"), Cow::Borrowed(_))); println!("{}", normalize("in_stock"));}