Here's how to use Cow
in your case:
use std::borrow::Cow;let condition = false;let a: String = "a".to_string();let r: Cow<str> = if condition { Cow::from(&a)} else { let b: String = "b".to_string(); Cow::from(b)};
For your second example, you have to add Clone
. For an arbitrary clone type, you also have to instantiate the variants directly.
use std::borrow::Cow;#[derive(Clone)]struct S(i32);let condition = false;let a: S = S(0);let r: Cow<S> = if condition { Cow::Borrowed(&a)} else { let b: S = S(1); Cow::Owned(b)};
And this does mean that you can use Cow<String>
in the same way.
use std::borrow::Cow;let condition = false;let a: String = "a".to_string();let r: Cow<String> = if condition { Cow::Borrowed(&a)} else { let b: String = "b".to_string(); Cow::Owned(b)};
It's better to use Cow<str>
for the same reason that it's better to use &str
instead of &String
: &str
has a smaller representation in memory (one fewer pointer-sized field), and has all of the same capabilities.