Sunday, June 05, 2022

How not to start with Rust

My attempt to translate an existing C project to Rust stalled after a few days as I struggled to express the concepts that I used so easily in C.

In the C code, I used a bump allocator, and I had data structures that ensured the stability of pointers. Thus I could just reference objects by their pointers everywhere and at the end, all objects were discarded by destroying the allocator.

In Rust expressing this is hard, and actually, impossible without the use of unsafe code. There is no way to convince the Rust compiler that a reference is safe if its stored in multiple places, because while I know that the memory pointed by the reference is held by the allocator and is safe, the compiler cannot see this at compile time, and therefore will not allow you to code this way.

I got bogged down trying to think of ways in which I could achieve what I had in C. This was a bit like trying to run before learning to walk.

Normally I prefer to learn a new programming language by just coding in it. That was one of the mistakes I made with Rust. Rust is one of those languages that you need to spend time learning by reading good books. Despite its popularity, the language specification in The Rust Reference appears to be strangely deficient and unfinished; I struggled to find good description of how lifetime annotation works. The Rust Programming Language book is a good starting point, but doesn't really go into in-depth discussion of any topic. Examples tend to be simplistic too. For instance in the chapter on collections, it wasn't deemed necessary to explain / illustrate how to use user defined types as keys and values in a hash map. A much better book for learning beyond the basics is Programming Rust.