LizzAlice
LizzAlice

Reputation: 720

Why do I get the error "expected integral variable, found Option" when matching on an integer?

I am trying to use match in Rust. I wrote a function:

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

But I'm getting the error:

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<_>`

I tried something like let try: i32 = 3; to make sure that try is an integral value, but I still get the same error.

Upvotes: 5

Views: 10814

Answers (2)

ljedrz
ljedrz

Reputation: 22233

In match expressions the type of the value you are matching on must correspond to the variants in the block following it; in your case this means that try either needs to be an Option or the match block needs to have integral variants.

I highly recommend reading The Rust Book; Rust is strongly typed and this is one of the most basic concepts you will need to familiarize yourself with.

Upvotes: 1

user94559
user94559

Reputation: 60143

I think you want this:

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

The issue is that you're trying to match an integer against Some(...) and None, which are Options. This doesn't really make sense... an integer can never be None.

Instead, I think you want to use the type Option<i32> and convert it to an i32 by using a default value. The above code should accomplish that. Note that if that's all you're trying to do, this is an easier way:

let x = try.unwrap_or(0);

Upvotes: 7

Related Questions