Copy-on-Write
Recipe | Crates |
---|---|
Convert Cow to &str | |
Convert Cow to String |
The type std::borrow::Cow
is a smart pointer providing clone-on-write functionality.
Convert Cow
to &str
Use std::borrow::Borrow
⮳:
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
⮳:
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:
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:
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
Use std::string::ToString
⮳:
fn main() { let example = std::borrow::Cow::from("example"); let s = example.to_string(); println!("{}", s); }
Use std::borrow::Cow::into_owned
⮳:
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
⮳:
fn main() { let example = std::borrow::Cow::from("example"); println!("{}", example.as_ref().to_owned()); }
These examples were adapted from a StackOverflow discussion⮳
[cow: add more (P1)](https://github.com/john-cd/rust_howto/issues/620)