Cow for clone-on-write to avoid unnecessary allocations

Marcus Chen Jan 2026
1 tab
use std::borrow::Cow;

fn ensure_prefix(input: &str) -> Cow<str> {
    if input.starts_with("https://") {
        Cow::Borrowed(input)
    } else {
        Cow::Owned(format!("https://{}", input))
    }
}

fn main() {
    let url1 = ensure_prefix("https://example.com");
    let url2 = ensure_prefix("example.com");
    println!("{}, {}", url1, url2);
}
1 file · rust Explain with highlit

Cow<'a, T> (clone on write) holds either a borrowed or owned value. It borrows when possible and clones only when mutation is needed. I use Cow<str> for APIs that might need to modify a string: if no changes are needed, it stays borrowed; if changes are made, it clones. This optimizes the common case (no mutation) while supporting the less common case (mutation). The .to_mut() method clones if needed and returns a mutable reference. Cow is useful for config processing, normalization, and string transformations where most inputs don't need changes. It's a zero-cost abstraction when borrowing and a one-time clone when mutating.