FerrousPath

Level 1 · Foundations· Lesson 2 of 10 · 20 min

Variables and types

Bindings, mutability, shadowing, and the scalar and compound types every program is built from.

Bindings are immutable by default

let binds a name to a value. Unless you say otherwise, that binding cannot be reassigned.

fn main() {
    let x = 5;
    println!("x = {x}");
    x = 6; // ❌ error[E0384]: cannot assign twice to immutable variable
    println!("x = {x}");
}

Add mut to opt in to mutation:

fn main() {
    let mut count = 0;
    count += 1;
    count += 1;
    println!("count = {count}");
}

Why this default? Most values never change after they are created, and a reader who sees no mut knows that for certain. Mutability becomes something you notice.

Shadowing

You can declare a new binding with the same name. The old one is shadowed, not modified — and the new one may have a different type.

fn main() {
    let input = "  42  ";
    let input = input.trim();              // still a &str, but trimmed
    let input: i32 = input.parse().unwrap(); // now an i32
    println!("{}", input + 1);
}

Shadowing is idiomatic for this kind of step-by-step refinement. It avoids names like input_str, input_trimmed, input_num.

Constants

const MAX_CONNECTIONS: u32 = 1_000;

fn main() {
    println!("{MAX_CONNECTIONS}");
}

A const must have a type annotation and a value computable at compile time. It is inlined wherever it is used. Underscores in numeric literals are just for readability.

Scalar types

Kind Types Notes
Signed integers i8 i16 i32 i64 i128 isize i32 is the default
Unsigned integers u8 u16 u32 u64 u128 usize usize indexes collections
Floating point f32 f64 f64 is the default
Boolean bool true or false; not an integer
Character char A 4-byte Unicode scalar value, not a byte

Rust infers types where it can and never converts between numeric types implicitly. Use as for a cast that may truncate, or From/TryFrom for conversions that state whether they can fail.

fn main() {
    let a: i32 = 7;
    let b: f64 = 2.0;
    // let c = a / b;                 // ❌ would not compile: mismatched types
    let c = a as f64 / b;             // explicit cast
    let big: i64 = i64::from(a);      // lossless, cannot fail
    let small = u8::try_from(300i32); // may fail: returns a Result
    println!("{c} {big} {small:?}");

    let heart = '❤';
    println!("{heart} is {} bytes as a char", std::mem::size_of::<char>());
}

Integer overflow

Overflow is a bug Rust refuses to make silent. In debug builds, arithmetic that overflows panics. In release builds it wraps (two’s complement). When you want a specific behaviour, say so:

fn main() {
    let x: u8 = 250;
    println!("{:?}", x.checked_add(10));    // None
    println!("{}", x.wrapping_add(10));     // 4
    println!("{}", x.saturating_add(10));   // 255
    println!("{:?}", x.overflowing_add(10)); // (4, true)
}

Compound types

A tuple groups a fixed number of values of possibly different types. An array holds a fixed number of values of one type; its length is part of its type.

fn main() {
    let point: (i32, i32, &str) = (3, -4, "origin-ish");
    let (x, y, label) = point; // destructuring
    println!("{label}: {x}, {y}; first field again: {}", point.0);

    let primes: [u32; 5] = [2, 3, 5, 7, 11];
    let zeros = [0u8; 16]; // sixteen zeros
    println!("{} {} {}", primes[0], primes.len(), zeros.len());

    let unit = (); // the empty tuple, called "unit": the type of "nothing interesting"
    println!("{unit:?}");
}

Indexing an array out of bounds is checked. With a constant index the compiler rejects it; with a runtime index the program panics rather than reading memory it does not own. That check is one of the ways Rust keeps the promise from lesson 1.

Type inference

Rust’s inference looks at how a value is used, not only how it is created:

fn main() {
    let mut numbers = Vec::new(); // element type unknown here…
    numbers.push(1u64);           // …decided here
    let parsed = "17".parse::<u8>().unwrap(); // "turbofish" names the target type
    println!("{numbers:?} {parsed}");
}

When the compiler says type annotations needed, it is telling you nothing in the code pins the type down. Add an annotation on the let or use the ::<T> turbofish.

Exercises

  1. Write a program that converts a temperature in Fahrenheit (stored in a variable) to Celsius and prints both with one decimal place ({:.1}).
  2. Declare a tuple holding your name, age and height in metres, destructure it, and print a sentence.
  3. Predict the output, then run: let x = 5; let x = x * 2; { let x = x + 1; println!("{x}"); } println!("{x}");
Solution to 3

It prints 11 then 10. The inner x shadows the outer one only inside the block; when the block ends, the outer binding (10) is visible again.

Check your understanding

Pick an answer to see the explanation.

  1. 1.What happens when you compile let x = 5; x = 6;?

  2. 2.What is the type of x in let x = 2.0;?

  3. 3.In a debug build, what does let x: u8 = 255; let y = x + 1; do at runtime?

Key terms in this lesson

Finished the lesson and the exercises?