使用时unwrap_or
,如何获得String
?
我已经把我的问题提炼成这个(类型注释比需要的多):
fn main() {
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar");
}
这(合理地)告诉我我们需要 aString
而不是 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`
所以我尝试提供想要的类型。
blah = opt.unwrap_or("bar".to_string());
但我被告知:
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`