Programming Servo: How to match
Today, let’s share some lessons learned from contributing to Servo, which is a great way to learn Rust.
We all love Rust’s
match statement. However, like almost everything else in programming, it can quickly get out of hand and result in difficult to read code, in this particular case due to increasing level of nesting in your code.
For a good intro, see https://doc.rust-lang.org/book/second-edition/ch06-02-match.html
Lesson 1: Reduce indentation by flattening your matches
Next time, when you’re about to add some logic inside an arm of your match statement, ask yourself the following: “could I assign the value that I’ve just extracted out of this match, to a
let outside of the match, and then do the logic outside of it?”.
This techniques helps reducing the nesting levels of your code, making it more readable.
Lesson 2: Return right inside your matches
There are other things that you actually really want to do right inside the match, such as returning “early” out of a function, and it can be combined neatly with the technique from lesson 1.
Basically, if a given arm of your arm gives you immediately what you need to return from your function call, just return it right there from the match. It might seem weird at first if the other arm of the match actually assigns something to a
let, like is done here, but it’s actually valid(and beautiful).
If your function doesn’t return anything, just do a plain
return, like here.
In some cases, you could also consider replacing a match statement with using the
?operator. If you are matching over a
Result, and doing an early
return Err, it could be replaced by a
let ok_result = func_returning_result()?;. This statement will assign the
Ok(something)to your let, and do an early return in the case of an
?operator is also in the process of being expanded to cover other types than
Result, by way of the
Trytrait, see https://github.com/rust-lang/rfcs/blob/master/text/1859-try-trait.md, with an “unstable” implementation for
Optionalready shipped in https://github.com/rust-lang/rust/pull/42526
Lesson 3: you can also continue…
If you’re matching inside a loop, like here, when the match arm is basically saying, ‘nothing to do here, let’s move on to the next iteration’, one can use
continue, to do just that.
And just like
return, the other arm of the match can actually assign a value to a
let, and allow the algorithm to use it in the current iteration.