July 29, 2015

Rustc's awesome error explanations

One of my favourite features of Rust so far is not language feature, but a delightful compiler feature that made me smile when I discovered it. That feature is rustc --explain.

It works like this: I am writing some Rust code, and I make an error; Maybe I didn’t correctly implement all branches of my match statement.

fn main() {
    match 1 {
        1 => {}

When I try and build my program, it fails!

[matth@tomoe] ~ % rustc foo.rs
foo.rs:2:5: 4:6 error: non-exhaustive patterns: `_` not covered [E0004]
foo.rs:2     match 1 {
foo.rs:3         1 => {}
foo.rs:4     }
foo.rs:2:5: 4:6 help: run `rustc --explain E0004` to see a detailed explanation
error: aborting due to previous error

The Rust team have spent a lot of time, and done a great job, making the compiler error messages friendly and helpful; but they’re not exhaustive and sometimes you need more information.

For this you can use the --explain flag to the Rust compiler. Every Rust error should show you an error code in brackets after the message - In this example the error code is E0004

The compiler is even telling us what to do next: just pass the error code to the --explain flag to get more detailed information that will help us solve our problem.

[matth@tomoe] ~ % rustc --explain E0004
This error indicates that the compiler cannot guarantee a matching pattern for
one or more possible inputs to a match expression. Guaranteed matches are
required in order to assign values to match expressions, or alternatively,
determine the flow of execution.

If you encounter this error you must alter your patterns so that every possible
value of the input type is matched. For types with a small number of variants
(like enums) you should probably cover all cases explicitly. Alternatively, the
underscore `_` wildcard pattern can be added after all other patterns to match
"anything else".

This is great! I’d love to see more languages implement something like this. It’s almost as if the compiler itself is trying to help you learn the language!

This is a lot of work, so not all errors are covered yet, but the Rust team are doing a great job, and if you want to get involved there is an open issue on Github for the missing errors. This links to a shared Google Document that documents the progress that has been made so far.