Matching

Let's look at a very unpleasant code block and then examine what it means:

fn my_test(x: i32) -> String 
{ 
    if x == 1 
    {   
        return "one".to_owned(); 
    } 
    else if x == 2 
    { 
        return "two".to_owned(); 
    } 
    else if x == 3 
    { 
        return "three".to_owned(); 
    } 
    return "not found".to_owned(); 
} 

The code takes an i32 parameter and tests to see what it equals. If the condition is met, some text is returned for that number; otherwise, "not found" is returned.

This is a trivial example, but imagine if you're testing against 10 different conditions; the if-else construct will become ugly.

If we were in C, we could use switch/case and Rust can also do something similar, but the keyword is match instead. If we used the match expression, our function would be as follows:

fn my_test(x: i32) -> String 
{ 
    let mut t = "".to_owned(); 
    match x 
    { 
        1 => t = "one".to_owned(), 
        2 => t = "two".to_owned(), 
        3 => t = "three".to_owned(), 
        _ => t = "not found".to_owned() 
    } 
    return t; 
} 

In this instance, when x is matched to the value inside of the match expression, t is assigned. If it is not matched (_ = > ...), then t is set to be not found. There must be a _ wildcard pattern case within the match. This is down to Rust enforcing exhaustiveness checking. In other words, until the _ wildcard is reached, Rust assumes that there must be other values to attempt to match.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset