I want to write the following with if let
but Ok(config)
does not provide the type for 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. The success type is not inferred.
This has nothing to do with the match
or the if let
; the type specification is provided by the assignment to result
. This version with if let
works:
extern crate toml;
fn main() {
let result: Result<i32, _> = toml::from_str("");
if let Ok(config) = result {
// ...
}
}
This version with match
does not:
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:
match toml::from_str::<i32>("") {
// ^^^^^^^
Ok(config) => {},
_ => {}
}
if let Ok(config) = toml::from_str::<i32>("") {
// ^^^^^^^
}
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With