Rust Variables and Data Types
In Rust, variables cannot change unless you say so. This makes programs easier to trust.
Immutable by Default
Example
fn main() {
let price = 500;
println!("Price: {}", price);
// price = 600; // error: cannot assign twice to immutable variable
}Price: 500
mut: Variables That Can Change
Add mut to let a variable change:
Example
fn main() {
let mut balance = 1000;
balance += 250;
balance -= 100;
println!("Balance: {}", balance);
}Balance: 1150
Rust makes you choose mut on purpose. When you read code, you know straight away which values may change.
Constants
A constant is always fixed, must have a type, and is written in capital letters:
Example
const MAX_STUDENTS: u32 = 30;
fn main() {
println!("Class size limit: {}", MAX_STUDENTS);
}Class size limit: 30
Shadowing
You can declare a new variable with the same name. The new one hides (shadows) the old one. It can even have a different type.
Example
fn main() {
let input = "42";
let input: i32 = input.parse().unwrap();
let input = input * 2;
println!("{}", input);
let spaces = " ";
let spaces = spaces.len();
println!("{}", spaces);
}84 3
Shadowing is different from mut: each let creates a brand new variable.
Scalar Types
| Type | Stores | Example |
|---|---|---|
i32 | Signed whole number (default integer) | -15 |
u32 | Unsigned whole number (no negatives) | 15 |
i64, u64 | Bigger whole numbers | 9000000000 |
f64 | Decimal number (default float) | 3.14 |
bool | true or false | true |
char | One Unicode character, single quotes | 'R' |
The i means signed (can be negative), u means unsigned, and the number is the size in bits. usize is used for positions and lengths.
Tuples and Arrays
A tuple groups values of different types. An array holds values of the same type with a fixed length.
Example
fn main() {
let student: (&str, u32, f64) = ("Ali", 19, 3.4);
println!("{} is {} with GPA {}", student.0, student.1, student.2);
let (name, age, _) = student;
println!("{name} {age}");
let marks = [70, 85, 90];
println!("First: {}, count: {}", marks[0], marks.len());
println!("{:?}", marks);
let zeros = [0; 4];
println!("{:?}", zeros);
}Ali is 19 with GPA 3.4 Ali 19 First: 70, count: 3 [70, 85, 90] [0, 0, 0, 0]
[0; 4] means "four zeros".
Type Conversion
Rust never converts number types by itself. Use as for numbers and parse for text:
Example
fn main() {
let marks: i32 = 45;
let total: i32 = 60;
let percent = marks as f64 / total as f64 * 100.0;
println!("{}%", percent);
let n: i32 = "250".parse().unwrap();
println!("{}", n + 50);
}75% 300
unwrap() takes the number out of the result. If the text is not a number, the program stops with an error. You will learn better ways in the structs and enums lesson.
Exercise
Exercise
Which line creates a variable whose value can be changed?
