Rust Programming: Patterns That Bind to Values

0

Patterns that bind to values are a feature of Rust's match expression that allow us to extract values out of enum variants. This is done by adding a variable to the pattern that matches the value of the enum variant. Here is an example of patterns that bind to values:

enum Color {

    Red,

    Green,

    Blue,

}


fn print_color(color: Color) {

    match color {

        Color::Red => println!("The color is red"),

        Color::Green => println!("The color is green"),

        Color::Blue => println!("The color is blue"),

    }

}

In this code, the pattern Color::Red binds the value of the Red variant to the variable color. This allows us to use the value of color in the code for that arm of the match expression. For example, if we call print_color(Color::Red), the value of color will be Red and the println! expression will print "The color is red".

Patterns that bind to values are a powerful feature of Rust's match expression that allow us to extract values out of enum variants and use them in our code.

Post a Comment

0Comments
Post a Comment (0)