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



我试图在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 s(匹配。这并没有真正的意义...整数永远不可能是None

相反,我认为您要使用默认值使用Option<i32>类型并将其转换为i32。以上代码应该实现这一目标。请注意,如果您要这样做,这是一种更简单的方法:

let x = try.unwrap_or(0);

match中表达您所匹配的值的类型必须对应于块之后的块中的变体;在您的情况下,这意味着try要么需要是Option,要么match块需要具有整体变体。

我强烈建议您阅读《锈书》;生锈是强烈打字的,这是您熟悉自己所需的最基本概念之一。

最新更新