November 2017
Beginner
308 pages
8h 32m
English
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: ...
Read now
Unlock full access