Monday, March 27, 2023

Rust

I've just recently completed an online course for Rust. I find Rust a very interesting language. I've always subscribed to the philosophy that the compiler should try as hard as possible to find errors for you. While I can appreciate an interpreted language like Python, in my experience Python requires an enormous amount of discipline to write a large Python program with many team members. In a language like Java, the compiler is doing so much tedious work by making sure you don't pass arguments or assign variables of the wrong type.

The interesting thing about Rust is that it doesn't have a garbage collector. Rust is a replacement for system languages like C or C++, where it is not always possible or desirable to have a garbage collector thread working away int he background.

While I'm not the best at C++, I have used it enough to realize that managing memory consumes a big chunk of mental overhead. I know about patterns like using the stack to free resources and I know all about memory pools, but I don't feel comfortable enough with C++ to say that I've fully assimilated all the patterns good C++ programmers use to keep themselves out of trouble. Rust is a window on that world.

Whenever you find people using a (good) pattern, other people will try to make a computer language that accommodates it. Using a stack while in assembly leads to things like procedures. The judicious use of goto leads to things like the break or return statement. Even recently, a style of programming that tries to make everything immutable leads to a type of programming called functional programing. Rust tells me about the types of patterns C++ programmers use to keep themselves from making mistakes.

Rust has this thing called the borrow checker. It's primary purpose it to make sure that only one chunk of code owns a variable or piece of memory. Without a garbage collector, every object must be manually freed exactly once. This functionally means that every object has an owner who's job it is to manage the lifetime of the object and free it when it's not used anymore.

The borrow checker essentially forces you to make clear which functions are merely using an object and which function owns the object. It works surprisingly well although I've heard complaints that for things like a tree structure with a parent back links you have to do some serious thinking to make it all work. Honestly, I remember writing a doubly linked list in C++ and felt it was like watching bender putting on his own arms.

In any case, I hope I have the privilege of working on a Rust code base at some point. At the very least it will make me a better C++ programmer.