Three things I wish I’d known learning Rust
Summary
At Screenleap we’re running Rust in production, yet I feel like I’m still only scratching the surface of the language. Hopefully you will enjoy learning Rust as much as I am.
It will take longer to learn than most languages
As professional programmers we expect to learn a new language every few years, and it usually doesn’t take very long. Learning Rust was different for me for three reasons:
-
Rust is a big language. The official book is over 500 pages, and it has to skip quite a lot.
-
It introduces new concepts: Ownership, Lifetimes, Traits. Those aren’t in any other language I’ve used.
-
It makes explicit things that other languages hide. In other languages you can happily pass values around and change them from anywhere. That language is doing lots of things inside to make it work for you. Rust gives you control over those things. If you have a C++ background this part will be easier for you.
The good news is there are excellent resources for learning Rust, and a very helpful community. The offical Rust Book is the ideal place to start. Rust By Example helped me a lot too.
The standard library is small, you will need dependencies
Learning a language means also learning its standard library, so at first I try to avoid dependencies. That’s not possible in Rust.
There are several semi-official crates that most projects use, and you should pretend those are standard library. Examples include: log, chrono, rand, clap, reqwest and serde.
Once I accepted that the standard library isn’t batteries-included I found it easy to identify the library I needed. The Rust Cookbook is a great place to look, as is the Most Downloaded on crates.io.
A lot of behavior is in Traits
In Rust a lot of methods are not on the object itself, but were added by a trait. In this context think of a trait as a mix-in, a way to add behavior (methods) to an existing object.
This can make it hard to find the method you need. For example, the File object has no obvious methods to either read or write. You have to look under “Trait Implementations”, expand “Read” trait, and finally expand “Show hidden undocumented items”.
Methods will appear on your object when you import a trait. If you have a File
struct, you can’t read anything from it until you import the trait that attaches those methods (use std::io::Read
). You will sometimes see code call methods on a type (even built in ones like f64
) that you can’t call. That’s because they are importing a trait that you aren’t. So use the trait, Luke.