45 Mins

2. Rust Variables and Data Types

Core Concept

A variable is a named container that holds a value in memory. Rust is a statically typed language, meaning you must declare the type of every variable, though the compiler can often infer the type.

Variables in Rust are immutable by default. This is a key difference from many other languages and is a core part of Rust's safety guarantees. To make a variable mutable, you use the mut keyword.

Declaring Variables

In Rust, you declare a variable using the let keyword. By default, variables are immutable. You can optionally annotate the type.

Rust
fn main() {
    // Immutable variable (default)
    let age = 25;
    let height = 5.9;
    let grade = 'A';
    let is_active = true;
    
    // With type annotation
    let name: &str = "Alice";
    
    // Mutable variable
    let mut score = 100;
    score = 95;  // Can be changed
    
    println!("Age: {}", age);
    println!("Height: {}", height);
    println!("Grade: {}", grade);
    println!("Active: {}", is_active);
    println!("Name: {}", name);
    println!("Score: {}", score);
}
OutputAge: 25 Height: 5.9 Grade: A Active: true Name: Alice Score: 95

Notice that age, height, grade, and is_active are immutable by default. score is mutable because we used the mut keyword. Rust automatically infers the types of variables from their values.

Variable Naming Rules

Variable names in Rust must follow specific rules. Breaking these rules will cause a compilation error.

Rust
fn main() {
    // Valid variable names
    let my_age = 30;
    let _score = 100;
    let player_health = 75;
    let PlayerHealth = 100;    // Different from player_health
    
    // Snake case is the Rust convention for variables
    let my_variable_name = 42;
    
    println!("my_age: {}", my_age);
    println!("_score: {}", _score);
    println!("player_health: {}", player_health);
    println!("PlayerHealth: {}", PlayerHealth);
    println!("my_variable_name: {}", my_variable_name);
}
Outputmy_age: 30 _score: 100 player_health: 75 PlayerHealth: 100 my_variable_name: 42

Variable names must start with a letter or underscore, can contain letters, numbers, and underscores, and are case-sensitive. Rust uses snake_case for variable names, which is the convention.

Common Data Types

Rust provides several basic data types organized into two categories: scalar types (single values) and compound types (collections of values).

Rust
fn main() {
    // Scalar Types
    let integer: i32 = 42;         // Signed 32-bit integer
    let unsigned: u32 = 100;       // Unsigned 32-bit integer
    let float: f64 = 3.14159;      // 64-bit floating point
    let boolean: bool = true;      // Boolean
    let character: char = 'A';     // Character (Unicode)
    
    // Compound Types
    let tuple: (i32, f64, char) = (42, 3.14, 'A');
    let array: [i32; 5] = [1, 2, 3, 4, 5];
    
    println!("Integer: {}", integer);
    println!("Unsigned: {}", unsigned);
    println!("Float: {}", float);
    println!("Boolean: {}", boolean);
    println!("Char: {}", character);
    println!("Tuple: {:?}", tuple);
    println!("Array: {:?}", array);
}
OutputInteger: 42 Unsigned: 100 Float: 3.14159 Boolean: true Char: A Tuple: (42, 3.14, A) Array: [1, 2, 3, 4, 5]

Rust has integers of different sizes (i8, i16, i32, i64, i128, isize for signed; u8, u16, u32, u64, u128, usize for unsigned). f32 and f64 are for floating-point numbers. char is Unicode (4 bytes).

Constants

Constants in Rust are declared with the const keyword and must have a type annotation. They are always immutable and can only be set to a constant expression (computed at compile time).

Rust
// Constants must be typed and can be declared at module level
const TAX_RATE: f64 = 0.08;
const MAX_SCORE: u32 = 100;
const APP_NAME: &str = "Rust Mastery";

fn main() {
    let price = 49.99;
    let total = price + (price * TAX_RATE);
    
    println!("App: {}", APP_NAME);
    println!("Price: ${}", price);
    println!("Total: ${:.2}", total);
    println!("Max Score: {}", MAX_SCORE);
    
    // Cannot reassign constants
    // const TAX_RATE = 0.10; // Error: cannot reassign
}
OutputApp: Rust Mastery Price: $49.99 Total: $53.99 Max Score: 100

Constants are different from variables. They are always immutable and can be declared in any scope, including the module level. Constants are inlined at compile time.

Type Inference

Rust has powerful type inference. The compiler can often deduce the type of a variable from its value, but you can also explicitly annotate types when needed.

Rust
fn main() {
    // Type inference
    let number = 42;           // i32 by default
    let pi = 3.14;             // f64 by default
    let letter = 'Z';          // char
    let name = "Rust";         // &str (string slice)
    
    // Explicit type annotation
    let explicit_i32: i32 = 42;
    let explicit_u64: u64 = 100;
    let explicit_f32: f32 = 3.14;
    
    // Type suffix
    let suffix_i32 = 42i32;
    let suffix_u64 = 100u64;
    let suffix_f32 = 3.14f32;
    
    println!("number: {}", number);
    println!("pi: {}", pi);
    println!("letter: {}", letter);
    println!("name: {}", name);
}
Outputnumber: 42 pi: 3.14 letter: Z name: Rust

Rust infers i32 for integer literals and f64 for floating-point literals by default. You can use type suffixes (like 42i32) or explicit annotations to specify the exact type.

Knowledge Check

Ready to test your understanding of 2. Rust Variables and Data Types?

Back