我想写以下内容if let但Ok(config)没有提供类型toml::from_str
let result: Result<Config, _> = toml::from_str(content.as_str());
match result {
Ok(config) => {}
_ => {}
}
// if let Ok(config) = toml::from_str(content.as_str()) {
//
// }
Run Code Online (Sandbox Code Playgroud)
我尝试过Ok(config: Config)但没有运气。无法推断成功类型。
这与match或无关if let;类型规范由对 的赋值提供result。这个版本的if let作品:
extern crate toml;
fn main() {
let result: Result<i32, _> = toml::from_str("");
if let Ok(config) = result {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
此版本match没有:
extern crate toml;
fn main() {
match toml::from_str("") {
Ok(config) => {}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您实际上会使用成功值。根据用法,编译器可以推断类型,并且您不需要任何类型规范:
fn something(_: i32) {}
match toml::from_str("") {
Ok(config) => something(config),
_ => {}
}
if let Ok(config) = toml::from_str("") {
something(config);
}
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因您需要执行转换但不使用该值,您可以在函数调用中使用turbofish :
match toml::from_str::<i32>("") {
// ^^^^^^^
Ok(config) => {},
_ => {}
}
if let Ok(config) = toml::from_str::<i32>("") {
// ^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
3940 次 |
| 最近记录: |