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

标签 rust

我想用 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) 但没有成功。不推断成功类型。

最佳答案

这与matchif 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/

相关文章:

rust - 为什么元组或结构的大小不是成员的总和?

rust - 我们可以在箱子安装期间下载一些东西并设置环境变量吗?

rust - Rust 是否有 -Ofast -march=native 的等价物?

rust - "cannot infer type for ` T `"使用错误枚举变体时

rust - 我应该如何减少 Rust 类型签名的重复?

rust - Tokio mpsc 接收器上的非阻塞接收

rust - "cd"执行一系列命令时没有效果

UDP `join_multicast` 导致 OtherIOError

rust - 使用 Sled,我如何序列化和反序列化?

rust - 一次借用切片的索引和结构的字段时无法推断正确的生存期