rust - 为什么在匹配整数时会出现错误 "expected integral variable, found Option"?

标签 rust match

我正在尝试在 Rust 中使用 match。我写了一个函数:

fn main() {
    let try = 3;
    let x = match try {
        Some(number) => number,
        None => 0,
    };
}

但是我得到了错误:

error[E0308]: mismatched types
 --> src/main.rs:4:9
  |
4 |         Some(number) => number,
  |         ^^^^^^^^^^^^ expected integral variable, found enum `std::option::Option`
  |
  = note: expected type `{integer}`
             found type `std::option::Option<_>`

error[E0308]: mismatched types
 --> src/main.rs:5:9
  |
5 |         None => 0,
  |         ^^^^ expected integral variable, found enum `std::option::Option`
  |
  = note: expected type `{integer}`
             found type `std::option::Option<_>`

我尝试了类似 let try: i32 = 3; 的方法来确保 try 是一个整数值,但我仍然遇到同样的错误。

最佳答案

我想你想要这个:

fn main() {
    let try = Some(3);
    let x = match try {
        Some(number) => number,
        None => 0,
    };
}

问题是您正在尝试将整数与 Some(...) 进行匹配和 None , 这是 Option秒。这真的没有意义......整数永远不可能是None .

相反,我认为您想使用类型 Option<i32>并将其转换为 i32通过使用默认值。上面的代码应该可以做到这一点。请注意,如果这就是您要做的全部,那么这是一种更简单的方法:

let x = try.unwrap_or(0);

关于rust - 为什么在匹配整数时会出现错误 "expected integral variable, found Option"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44795582/

相关文章:

rust - 如何在不移动自身的情况下消除混合 Iterator 和 Futures 调用链的歧义?

MySQL MATCH AGAINST 不工作

regex - 如何在 Perl 中进行条件贪婪匹配?

Excel 从两个表中查找最后一个匹配项

rust - 当我在 Windows 上运行 Rust 应用程序时,着色可以与 Cargo Run 一起使用,但在直接使用二进制文件时它会完全中断。为什么?

ubuntu - spl-token : error while loading shared libraries: libssl. so.1.1:无法打开共享对象文件:没有这样的文件或目录

docker - 为什么在交叉编译为 musl 时 Rust 文档测试没有在 Docker 中执行?

rust - rust 迹所有权-由于存在 “behind a shared reference”而无法移动

python - 为什么使用正则表达式 finditer() 而不是 findall()

算法:将可加入游戏的用户与离他最近的用户匹配