2022-04-28

Structual Pattern Matching with Rust

Rust is so cool!

Let's say I want to check a struct to see if it has a field or not, and based on that, generate a new value for said field.


fn match() {
    let mut shortcode = String::new();
    // check if the user wants the shortcode to be generated or if they want us to generate one
    match &new_url.shortcode {
        Some(custom_shortcode) => {
            shortcode = custom_shortcode.to_string();
        }
        None => {
            // need to generate
            shortcode = generate_random_shortcode();
        }
    }
}

I can instead do -

fn match() {

    let mut shortcode = match &new_url.shortcode {
        Some(custom_shortcode) => {
            custom_shortcode.to_string();
        }
        None => {
            generate_random_shortcode();
        }
    };

}

How Cool is that?


Published on: 2022-04-28
Tags: rust latest WIP