I have a Cow
:
use std::borrow::Cow; // Cow = clone on write
let example = Cow::from("def")
I would like to get the def
back out of it, in order to append it to another String
:
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);
This does not work and I don't see the appropriate method in Cow
to get the &str
or String
back out.
How do I get a
&str
Use Borrow
:
use std::borrow::Borrow; alphabet.push_str(example.borrow());
Use AsRef
:
alphabet.push_str(example.as_ref());
Use Deref
explicitly:
use std::ops::Deref; alphabet.push_str(example.deref());
Use Deref
implicitly through a coercion:
alphabet.push_str(&example);
How do I get a
String
Use ToString
:
example.to_string();
Use Cow::into_owned
:
example.into_owned();
Use any method to get a reference and then call to_owned
:
example.as_ref().to_owned();
Pass a reference to example
(ie &example
) to push_str
.
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
alphabet.push_str(&example);
This works because Cow
implements Deref
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.