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

https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2Fservo%2Fservo%2Fpull%2F18676%23discussion_r144579123

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?”.

A simple example is found here. metadata is extracted out of the match, and assigned to let metadata. Next, it is used below the match.

This techniques helps reducing the nesting levels of your code, making it more readable.

Lesson 2: Return right inside your matches

https://github.com/servo/servo/pull/18676#discussion_r144590293

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 Err.
The ? operator is also in the process of being expanded to cover other types than Result, by way of the Try trait, see https://github.com/rust-lang/rfcs/blob/master/text/1859-try-trait.md, with an “unstable” implementation for Option already shipped in https://github.com/rust-lang/rust/pull/42526

Lesson 3: you can also continue…

https://github.com/servo/servo/pull/18676#discussion_r150271355

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.


Lesson 4: to learn Rust, have you considered contributing to Servo ?

Special thanks to jdm for providing the above linked-to feedback.