Welcome back to your Rust journey! Let's immerse ourselves in the exploration of Rust Variables — our key constructs. Similar to a cornerstone, variables provide structure to our code, enriching it with data and information.
A variable in coding is like a bookmark — a dedicated place in memory where a value is stored. This session aims to familiarize you with the concept of Rust variables, their declaration, naming rules, value assignments, and the concept of immutable variables.
Think of Rust variables as sticky notes imprinted with data. The short example below explains how to create a variable in Rust:
Let's break down each line of the code.
-
let number_of_stars: i32;This line is similar to creating a new sticky note and labeling it
number_of_stars. Theletkeyword is used to declare a variable namednumber_of_starswith the data typei32(a signed 32-bit integer). For now, don't worry about thei32part; we'll cover data types in a subsequent lesson. -
number_of_stars = 88;This line assigns the value 88 to the
number_of_starsvariable. It is like writing the information (88 in this case) on ournumber_of_starssticky note. -
println!("{}", number_of_stars);This line prints the value of the
number_of_starsvariable to the console. The{}is a placeholder that gets replaced by the value ofnumber_of_starswhen the program is run.
Rust also allows you to declare and assign a variable value simultaneously. Here's an example:
Notice how we did not have to explicitly declare number_of_stars as i32. Rust has a feature called type inference where Rust can automatically infer the type of number_of_stars. The default integer type in Rust is i32.
In Rust, variables are divided into two categories: mutable and immutable. By default, all variables in Rust are immutable, which means once a value is assigned to them, it cannot be changed. If you attempt to alter the value of an immutable variable, the Rust compiler will throw an error.
However, Rust gives you the ability to explicitly make a variable mutable using the mut keyword. A mutable variable is one whose value can be changed after it has been initially declared and assigned.
Rust allows us to change a variable's value using the = operator, which works much like writing a new note on a previously used sticky note.
