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
Cow
&str
Use std::borrow::Borrow
⮳:
/// Demonstrates the use of `Cow` (Clone-on-Write). fn main() { use std::borrow::Borrow; let mut my_string = String::new(); // Create a Cow that borrows the string literal "Example". let example = std::borrow::Cow::from("Example"); // Borrow the Cow and append it to my_string. my_string.push_str(example.borrow()); println!("{}", my_string); }
Use std::convert::AsRef
⮳:
fn main() { let mut my_string = String::new(); // Create a `Cow` that borrows the string literal "Example". let example = std::borrow::Cow::from("Example"); // Append the borrowed string to `my_string`. my_string.push_str(example.as_ref()); println!("{}", my_string); }
Use std::ops::Deref
⮳ explicitly:
/// This example demonstrates how to use `Cow` with `String` and `Deref`. /// It shows that you can use `Cow` to borrow a string slice and then /// use `deref()` to get a `&str` from it. 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(); // Create a Cow that borrows the string literal "example". let example = std::borrow::Cow::from("example"); // Append the borrowed string to my_string. my_string.push_str(&example); println!("{}", my_string); }
Convert Cow
to String
Cow
Use std::string::ToString
⮳:
fn main() { // Create a Cow from a string literal. let example = std::borrow::Cow::from("example"); // Convert the Cow to an owned String. let s = example.to_string(); println!("{}", s); }
Use std::borrow::Cow::into_owned
⮳:
fn main() { // Create a Cow<'static, str> from a string literal. let example = std::borrow::Cow::from("example"); // Convert the Cow to an owned String. println!("{}", example.into_owned()); }
Use any method to get a reference and then call std::borrow::ToOwned
⮳:
fn main() { // Create a Cow from a string literal. // In this case, it will be a Borrowed Cow. let example = std::borrow::Cow::from("example"); // Convert the Cow to a borrowed reference using `as_ref()`. // Then, clone the borrowed reference to create an owned `String`. println!("{}", example.as_ref().to_owned()); }
These examples were adapted from a StackOverflow discussion⮳.
Related Data Structures
- Strings.
See Also
- Lifetimes.
- Memory Management.
- Ownership & Borrowing.
- Rust Patterns.