Convert from options <& str> to Option <String>

What is the best practice for converting Option<&str> to Option<String> ? Strictly speaking, I am looking for a short equivalent:

 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())) 
+6
source share
2 answers

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 additional closure.

+3
source

map is the best choice:

 s.map(|s| s.to_string()) 
+7
source

Source: https://habr.com/ru/post/978911/


All Articles