From &str to Cow
— 1 minute read
Yesterday’s note on The Secret Life of Cows shows how to use Cow
as function return type when the function may return an owned type or a reference, e.g., String
or a &str
. Jow Wilm shows how to apply Cow
in a data structure with an ergonomic constructor:
struct Token<'a> {
raw: Cow<'a, str>
}
impl<'a> Token<'a> {
pub fn new<S>(raw: S) -> Token<'a> where S: Into<Cow<'a, str>> {
Token { raw: raw.into() }
}
}
// Create the tokens.
let token = Token::new("abc123");
let token = Token::new(String::new("abc123"));