While the preceding example is fairly compact, we can further reduce the footprint of the code by using match as an expression.
If you're used to ? in C#, you will be familiar with a construct such as the following:
var t = SomeCondition == 3 ? "three" : (SomeCondition == 4 ?
"four" : "not three or four");
This means that we can assign t to be three if SomeCondition == 3 else ifSomeCondition == 4, t = four. If this falls through, we can set t as not three or four.
It can get messy. Rust can do the same, only far more cleanly.
In the origin code, we had the following:
let mut t = "".to_string(); match x {
We can use match as an expression to set the value to be returned:
let t = match x { ... }; return t;
Or, more simply, by just returning the result of the match:
return match x { ... };
Or even more simply, when we remember that, in Rust, a block returns the result of its last expression when we omit the ;:
fn my_test(x: i32) -> String { match x { 1 => "one".to_owned(), 2 => "two".to_owned(), 3 => "three".to_owned(), _ => "not found".to_owned() }
}