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.
In Rust, you define a variable like so:
let x = 2;
Note that Rust also has
const. Chris Biscardi's post talks about it a bit.
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.
Since variable declarations are immutable by default you'll get an error if you try to change them.
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.
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.