Strings In Depth17 / 18
Up next

Borrow or own with Cow

use std::borrow::Cow;

// return the input untouched, or an edited owned copy
fn snake(s: &str) -> Cow<str> {
    if s.contains(' ') {
        Cow::Owned(s.replace(' ', "_"))
    } else {
        Cow::Borrowed(s)
    }
}

fn main() {
    println!("{}", snake("hello world"));
    println!("{}", snake("ok"));
}
What you're solving

allocate only when you must change it