Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on enum with value inside it?

Tags:

enums

rust

If I have a enum that imitates an option type, it can either contain some value, or nothing:

enum option {
    some(u8),
    none,
}

Then I can pattern match it like this:

let x = option::some(8);

match x {
    some => println!("some"),
    none => println!("none"),
}

But what if I want to pattern match the value inside the some? Intuitively, I think it would be something like so:

match x {
    some(x) => println!("{}", x),
    none => println!("none"),
}

But Rust has no idea what this is. I also try to see if the some itself is the u8 value:

match x {
    some => println!("{}", some),
    none => println!("none"),
}

This also does not work. How do I get the value inside the enum?

like image 932
Grazosi Avatar asked Jun 06 '26 09:06

Grazosi


1 Answers

This should work:

let x = option::some(8);
match x {
    option::some(x) => println!("{}", x),
    option::none => println!("none"),
}

But keep in mind this all-lower-case naming is against the standard Rust naming conventions. Your code will look much better like this:

enum Option {
    Some(u8),
    None
}

pub fn main() {
    let x = Option::Some(8);
    match x {
        Option::Some(x) => println!("{}", x),
        Option::None => println!("none"),
    }
}

You might see that note as nitpicking, but as you add more and more code, that will become a much bigger issue. So it's good to build the right habits from the beginning.

like image 103
at54321 Avatar answered Jun 07 '26 23:06

at54321



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!