[英]How do I specify a type that cannot be inferred when using if let?
I want to write the following with if let
but Ok(config)
does not provide the type for toml::from_str
我想用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()) {
//
// }
I tried Ok(config: Config)
without luck. 我没有运气就尝试了Ok(config: Config)
。 The success type is not inferred. 无法推断成功类型。
This has nothing to do with the match
or the if let
; 这与match
或if let
无关; the type specification is provided by the assignment to result
. 类型规范由result
的赋值提供。 This version with if let
works: if let
可以使用的if let
此版本:
extern crate toml;
fn main() {
let result: Result<i32, _> = toml::from_str("");
if let Ok(config) = result {
// ...
}
}
This version with match
does not: 具有match
版本不:
extern crate toml;
fn main() {
match toml::from_str("") {
Ok(config) => {}
_ => {}
}
}
In most cases, you'll actually use the success value. 在大多数情况下,您实际上将使用成功值。 Based on the usage, the compiler can infer the type and you don't need any type specification: 根据用法,编译器可以推断类型,您不需要任何类型说明:
fn something(_: i32) {}
match toml::from_str("") {
Ok(config) => something(config),
_ => {}
}
if let Ok(config) = toml::from_str("") {
something(config);
}
If for some reason you need to perform the conversion but not use the value, you can use the turbofish on the function call: 如果由于某种原因需要执行转换但不使用该值,则可以在函数调用中使用turbfish :
match toml::from_str::<i32>("") {
// ^^^^^^^
Ok(config) => {},
_ => {}
}
if let Ok(config) = toml::from_str::<i32>("") {
// ^^^^^^^
}
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.