Skip to content

Learning Rust - Ownership

Posted on:March 16, 2023 at 03:22 PM

Rust

The first thing that got my attention was Cargo which is Rust’s package manager and build system. It’s pretty easy to use and it comes overcharged right out of the gate with a way to initialize and run new projects by just one command each. The rust-analizer extension in vscode makes development so much easier, it features a server to start your new projects and inline visualization of typings (which I think is an awesome feature).

Common programming concepts

Rust is a very clear language when it comes write code in it, nothing we have seen before. Declaring variables is very straightforward and typing is not required. Here is an example:

declaration and printing of a variable

It looks weird if you come from something like javascript but this is just getting a random number from a range from 1 to 100.

Also, a simple example of functions and control flow with if:

code of a function with control flow

Loops are expressions in Rust, that means that they can return a value, which is crazy. You can do things like running a loop and assigning a value that could come out of it once the loop has finished. I know that in javascript you have things like map and forEach to run throught a whole array and return the array, and also reduce so we could get a single value, but this is like you could assign a for to a variable. And it looks like this:

a variable being assigned the returning value of a loop

Ownership

Here is where it starts to get difficult.

Rust’s compiler handles a concept called Ownership. Ownership is the way Rust ensures the code is “safe”, by safe it means that the code is not doing anything that could cause undefined behaviour, things like using memory that has already been freed or freeing memory before its use.

To figure out how to write safe code you have to do some mental gymnastics about which variable has write, read or ownership of data in the heap. It is difficult for me since I’ve been working with javascript for years now without having to worry about memory allocation, but it’s part of why I wanted to learn Rust in the first place.

At the end of the day, understanding pointers, memory allocation, and data structures is benefitial to me. Those are foundations that in a way I skipped by not finishing college and not actually needing them in my day to day writing React code.

Compiler

Rust’s compiler is a time saver, even though there is a learning curve in dealing with errors just as you write them without them being blatanly obvious, like a syntax error or a type error, Rust’s compiler catches the strangest of bugs that could happen in the future. This comes at the expense of having to carefully detail and think about the consequences the code you are writing could have.

Which I believe is a great tradeoff for the memory safe and secure code you are getting.