8
votes

What is the best practice to convert Option<&str> to Option<String>? Strictly speaking I'm looking for a concise equivalent of:

if s.is_some() {
    Some(s.to_string())
} else {
    None
}

and this is the best I could come up with:

s.and_then(|s| Some(s.to_string()))
2

2 Answers

4
votes

Another way is to use s.map(str::to_string):

let reference: Option<&str> = Some("whatever");
let owned: Option<String> = reference.map(str::to_string);

I personally find it cleaner without the extra closure.

9
votes

map is a better choice:

s.map(|s| s.to_string())

or

s.map(str::to_string)