Skip to main content

Variables, types, mutatbility, functions, and control flow

Variables

By default variables are immutable in Rust. Once you assign a value to it you cannot change it without explicitly marking the variable as mutable.

fn main() {
  	let x = 5;
  	x = 6; // compiler error
}

In order to make your variable mutable you must mark it with the mut keyword before the variable name like so:

fn main() {
	let mut x = 5;
    println!("{x}");
    x = 6;
    println!("{x}");
}
Constants

To declare a constant variable, a variable that you cannot change, you use the const keyword. Constants must have its value annotated. Meaning you have to explicitly give it its data type otherwise, it will not work.

const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
Shadowing

You are allowed to re-declare a variable of the same name. And the type of the variable can even be different, and this is referred to as shadowing.

fn main() {
	let x = 5;
  	let x = x + 1; // this is allowed
}

The final value of the variable x will be 6 because the x it is referring to in the assignment is still referring to the old variable, before it is updated as a new variable.

Shadowing is different than marking a variable as mut because the data type that you can reassign the data to can be completely different. In addition, if you don't use let and the variable isn't marked as mut then you will get a compile-time error. It isn't shadowing.

Shadowing is good if you want to reuse the same variable name after performing some transformation on the original value. For example

let spaces = "    ";
let spaces = spaces.len(); // This will update variable spaces to be the number of spaces

You cannot do this the data is mutable, because you cannot change the data type of the variable if it is marked as mutable. You can only change it to the value of the same type, not to a different type.

Data types