Match with an "undeclared" variable


#1

I was reading the Rust Programming Language Book, and I have stumbled at the part about if let.
The example in the book is the following:

let some_u8_value = Some(0u8);
match some_u8_value {
    Some(3) => println!("three"),
    _ => (),
}

This is apparently equivalent to:

if let some(3) = some_u8_value {
    println!("three");
}

I was not sure why this if let was needed, why not just:

if some_u8_value == Some(3) {
    println!("three");
}

So I was looking into match statements, and I found the following example:

let some_u8_value = Some(3u8);
match some_u8_value {
     Some(i) => println!("Matched: {}",i),
     None => ()
}

Which is apparently equivalent to:

let some_u8_value = Some(3u8);
if let Some(i) = some_u8_value {
    println!("assigned {} to i",i);
}

Where does the ā€œiā€ come from? It seems to be a "catch all for u8 values. I am under the impression that understanding the use of i here is the key to understanding the examples in the Rust Programming Language Book.

Thankyou for any help


#2

This is called pattern matching. You can declare bindings as part of a pattern, just like you can create bindings when using let. This is described in detail in the book: https://doc.rust-lang.org/book/second-edition/ch06-02-match.html#patterns-that-bind-to-values


#3

Match is for declaring new variables:

match 1 {
  x => {ā€¦}
}

is like

let x = 1; ā€¦