如何指定使用 if let 时无法推断的类型?

2023-11-26

我想写以下内容if let but 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)没有运气。无法推断成功类型。


这与match or the if let;类型规范由分配提供result。这个版本带有if let works:

extern crate toml;

fn main() {
    let result: Result<i32, _> = toml::from_str("");
    if let Ok(config) = result {
        // ... 
    }
}

这个版本带有match才不是:

extern crate toml;

fn main() {
    match toml::from_str("") {
        Ok(config) => {}
        _ => {}
    }
}

在大多数情况下,你实际上会use成功价值。根据用法,编译器可以推断类型,并且您不需要任何类型规范:

fn something(_: i32) {}

match toml::from_str("") {
    Ok(config) => something(config),
    _ => {}
}

if let Ok(config) = toml::from_str("") {
    something(config);
}

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

match toml::from_str::<i32>("") {
//                  ^^^^^^^
    Ok(config) => {},
    _ => {}
}

if let Ok(config) = toml::from_str::<i32>("") {
    //                            ^^^^^^^
}

也可以看看:

  • 当没有类型参数或归属时,如何暗示值的类型?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何指定使用 if let 时无法推断的类型? 的相关文章

随机推荐