如何指定使用 if let 时无法推断的类型? [英] How do I specify a type that cannot be inferred when using if let?

查看:31
本文介绍了如何指定使用 if let 时无法推断的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 if let 编写以下内容,但是 Ok(config) 没有提供 toml::from_str 的类型>

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()) {
//    
// }

我尝试了 Ok(config: Config) 没有运气.不推断成功类型.

I tried Ok(config: Config) without luck. The success type is not inferred.

推荐答案

这与 matchif let 无关;类型规范由对 result 的赋值提供.这个带有 if let 的版本有效:

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 {
        // ... 
    }
}

这个带有 match 的版本没有:

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);
}

如果由于某种原因您需要执行转换但不使用该值,您可以在函数调用中使用turbofish:

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>("") {
    //                            ^^^^^^^
}

另见:

这篇关于如何指定使用 if let 时无法推断的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆