-
Book Overview & Buying
-
Table Of Contents
Learning Rust
By :
Rust, as we have seen, contains many very powerful facilities. We will now consider two that are often seen, and then double back to examine how we can use the if let construct.
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...