Matching on variable value?


#1

Hi all,

is it possible to match on a variables value? I prepared a short snippet for pointing out my idea. I want the second match to print “goal” only if random_value is 2, but it should be variable. Currently goal is written by the match in the same way as rn in the first match.

extern crate rand;

fn main() {
    let random_number: Option<u8> = Some(rand::random::<u8>() % 3);
    
    // rn is written here - that's ok
    match random_number {
        Some(rn) => println!("num = {}", rn),
        None => println!("num = None"),
    }
    
    let goal = 2u8;
    
    // goal is written here - I want it to be constant like Some(0)
    match random_number {
        Some(0) => println!("zero"),
        Some(goal) => println!("goal"),
        Some(_) | None => println!("else"),
    }
}

Kind regards,
Roman


#2
Some(n) if n == goal => println!("goal"),

#3

Oh, so easy. Thank you very much!