When using unwrap_or
, how do I get a String
?
I've distilled my problem down to this (with more type annotation than needed):
fn main() {
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar");
}
This (reasonably) tells me that we need a String
not a &str
.
error[E0308]: mismatched types
--> src/main.rs:33:12
|
33 | blah = opt.unwrap_or("bar");
| ^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found &str
|
= note: expected type `std::string::String`
= note: found type `&str`
So I try to provide the type wanted.
blah = opt.unwrap_or("bar".to_string());
But I get told off:
error[E0308]: mismatched types
--> src/main.rs:33:26
|
33 | blah = opt.unwrap_or("bar".to_string());
| ^^^^^^^^^^^^^^^^^ expected &str, found struct `std::string::String`
|
= note: expected type `&str`
= note: found type `std::string::String`
error[E0308]: mismatched types
--> src/main.rs:33:12
|
33 | blah = opt.unwrap_or("bar".to_string());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found &str
|
= note: expected type `std::string::String`
= note: found type `&str`