如何 unwrap_or 到字符串
How to unwrap_or to String
使用 unwrap_or
时,如何获得 String
?
我已经将我的问题归结为这个(类型注释比需要的多):
fn main() {
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar");
}
这(合理地)告诉我我们需要 String
而不是 &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`
您看错了第一个错误。问题不在于传递给 unwrap_or()
的类型,而在于 unwrap_or()
返回的 类型 。由于您要分配给 String
,因此分配的右侧还必须提供 String
。只需在 unwrap_or
:
之后添加 to_string()
即可修复原始错误
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar").to_string();
当然 Option
也可以包含一个字符串,在这种情况下,您尝试的修复会很好地工作:
let mut blah: String;
let opt: Option<String> = Some("foo".to_string());
blah = opt.unwrap_or("bar".to_string());
请注意,这两个变量都不需要类型注释,Rust 的类型推断足够聪明,可以自行解决。
使用 unwrap_or
时,如何获得 String
?
我已经将我的问题归结为这个(类型注释比需要的多):
fn main() {
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar");
}
这(合理地)告诉我我们需要 String
而不是 &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`
您看错了第一个错误。问题不在于传递给 unwrap_or()
的类型,而在于 unwrap_or()
返回的 类型 。由于您要分配给 String
,因此分配的右侧还必须提供 String
。只需在 unwrap_or
:
to_string()
即可修复原始错误
let mut blah: String;
let opt: Option<&str> = Some("foo");
blah = opt.unwrap_or("bar").to_string();
当然 Option
也可以包含一个字符串,在这种情况下,您尝试的修复会很好地工作:
let mut blah: String;
let opt: Option<String> = Some("foo".to_string());
blah = opt.unwrap_or("bar".to_string());
请注意,这两个变量都不需要类型注释,Rust 的类型推断足够聪明,可以自行解决。