Copy-on-Write

std

The type std::borrow::Cow is a smart pointer providing clone-on-write functionality.

Convert Cow to &str

Use std::borrow::Borrow⮳:

#![allow(unused)]
fn main() {
    use std::borrow::Borrow;
    let mut my_string = String::new();
    let example = std::borrow::Cow::from("example");
    my_string.push_str(example.borrow());
    println!("{}", my_string);
}

Use std::convert::AsRef⮳:

#![allow(unused)]
fn main() {
    let mut my_string = String::new();
    let example = std::borrow::Cow::from("example");
    my_string.push_str(example.as_ref());
    println!("{}", my_string);
}

Use std::ops::Deref⮳ explicitly:

#![allow(unused)]
fn main() {
    use std::ops::Deref;
    let mut my_string = String::new();
    let example = std::borrow::Cow::from("example");

    my_string.push_str(example.deref());
    println!("{}", my_string);
}

Use std::ops::Deref⮳ implicitly through a coercion:

#![allow(unused)]
fn main() {
    let mut my_string = String::new();
    let example = std::borrow::Cow::from("example");
    my_string.push_str(&example);
    println!("{}", my_string);
}

Convert Cow to String

std

Use std::string::ToString⮳:

#![allow(unused)]
fn main() {
    let example = std::borrow::Cow::from("example");
    let s = example.to_string();
    println!("{}", s);
}

Use std::borrow::Cow::into_owned⮳:

#![allow(unused)]
fn main() {
    let example = std::borrow::Cow::from("example");
    println!("{}", example.into_owned());
}

Use any method to get a reference and then call std::borrow::ToOwned⮳:

#![allow(unused)]
fn main() {
    let example = std::borrow::Cow::from("example");
    println!("{}", example.as_ref().to_owned());
}

These examples were adapted from a StackOverflow discussion