Alex
Alex

Reputation: 33

In Rust, why do I not dereference on a match when it is required for if?

As a C programmer familiar with pointers and dereferencing, I'm working through a Rust tutorial, and have come across something I don't understand.

fn main() {
    let vector = vec![10, 20, 30, 40];
    for entry in &vector {
        if *entry == 30 { // I have to use a star (dereference) here...
            println!("thirty");
        } else {
            println!("{}", entry);
        }
        match entry { // ...but why do I not need a star here?
            30 => println!("thirty"),
            _ => println!("{}", entry), // or here?
        }
    }
}

Upvotes: 3

Views: 432

Answers (1)

Alex Vergara
Alex Vergara

Reputation: 2209

On the first case, your if statement is comparing against a value, so you must bring the value, aka dereferencing it, in order to compare values properly. Also, the loop over the vector is implying a .into_iter() call, that, given the context, gives you a reference &T to the current value in entry.

On the second match, the Rust compiler is applying automatic dereferencing, so the compiler already knows that you don't want to match against the pointer, but against the value. As others pointed out, match statements contain some ergonomics to make the code more readable.

Upvotes: 1

Related Questions