As with any programming language one of the main building blocks of Rust is variable usage.

Since I'm just learning Rust I wanted to really dive into the specifics around how it works.

Variable declaration

In Rust, you define a variable like so:

let x = 2;

By default, x is immutable, or read only. That's perhaps a bit confusing for those coming from JavaScript because it's the opposite.

Note that Rust also has const. Chris Biscardi's post talks about it a bit.

When using let a variable does not have to be typed. However, it can be.

let x: i32 = 2;

In the above example i32 is the type. Rust integers have more explicit typing than the Number you may be used to.

Mutable Variables

Since variable declarations are immutable by default you'll get an error if you try to change them.

Cannot assign twice to immutable variable error message.

If you want to create a variable that can change value you have to explicitly tell Rust that is your intention.

let mut x = 2;
x = 3;

mut stands for mutable. You are telling the Rust compiler that you will be changing this variable.

What's nice is that Rust holds you to this contract. If you declare a variable using mut and never change it you'll see this warning.

Variable does not need to be mutable warning.

And that's it

Rust wants you to be very clear about your intentions when creating variables. That might require a bit more upfront thinking, but it makes the error messages and warnings incredibly helpful!

Look out for my next post on ownership and reference in Rust.