Why I Use Rust

Before I began programming professionally, the majority of the code I wrote was in C. My university was a C shop, and I always found the idea that my code could run on the PDP-11 very romantic. However, once I started working at Google, I was writing C++ every day. The improvements were self-evident, but at Google’s scale, the footguns in C++ were also obvious. Google has strong style conventions, and these conventions forbid the worst parts of the C++ spec, and what is missed by human reviewers is often caught by automated linters. Nonetheless, this ‘idiomatic’ C++ is unreadable to anyone unfamiliar with modern C++.

Take initialization list syntax for example. It would not be uncommon to see code like:

MyLargeClass::MyLargeClass(int some_number, const std::string& name, const std::string& title)
    : my_number_(some_number), name_(name), title_(title),
      another_number_(another_number_init()),
      a_final_number_(std::max(0, final_number_init())) {}

If you are not familiar with C++ syntax, then this looks like garbage. Now, let’s introduce Rust:

pub fn new(some_number: int, name: String, title: String) -> MyLargeStruct {
    MyLargeStruct{
        my_number: some_number,
        name: name,
        title: title,
        another_number: another_number_init(),
        a_final_number: cmp::max(0, final_number_init()),
    }
}

Even if you are not familiar with Rust, I am sure you can read the Rust initializer. In fact the entire language seems designed to make grokking code easy. Another example is concurrent access to data. In C++, to have a int that is accessed from multiple threads, you need to use an instance of std::shared_ptr<int> and an instance of std::mutex to safe guard it. However, in Rust you would need a single Arc<Mutex<int>>. (“Arc” stands for “atomically reference counted” and it is the Rust equivalent of std::shared_ptr.) Instead of remembering to lock and unlock the mutex by hand, the Rust API requires us to unwrap a mutex to even access the int. It is impossible to incorrectly handle shared state and this is enforced by the language.

Because Rust is such an improvement over C++, I always choose the former over the latter when possible. In fact, the only time I write C++ code today is when there are libraries that only exist for C or C++. Today, these are usually graphics or simulation libraries, but Rust’s growing ecosystem is making C++-unique libraries more and more rare. I don’t know if I have already started my last new C++ project, but I suspect it is not too far off.