我想用 if let
编写以下内容,但是 Ok(config)
没有提供 toml::from_str
的类型/p>
let result: Result<Config, _> = toml::from_str(content.as_str());
match result {
Ok(config) => {}
_ => {}
}
// if let Ok(config) = toml::from_str(content.as_str()) {
//
// }
我尝试了 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 {
// ...
}
}
匹配
的版本不:
extern crate toml;
fn main() {
match toml::from_str("") {
Ok(config) => {}
_ => {}
}
}
在大多数情况下,您实际上会使用成功值。根据用法,编译器可以推断出类型,您不需要任何类型说明:
fn something(_: i32) {}
match toml::from_str("") {
Ok(config) => something(config),
_ => {}
}
if let Ok(config) = toml::from_str("") {
something(config);
}
如果出于某种原因您需要执行转换但不使用该值,您可以在函数调用中使用turbofish:
match toml::from_str::<i32>("") {
// ^^^^^^^
Ok(config) => {},
_ => {}
}
if let Ok(config) = toml::from_str::<i32>("") {
// ^^^^^^^
}
另见:
关于rust - 使用 if let 时如何指定无法推断的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841088/