Variables, mutability and constants

Immutable by default, typed by inference, and checked for overflow — Rust's variables are stricter than they look.

What you'll learn
  • Declare immutable and mutable bindings, and explain why immutable is the default
  • Read Rust's integer types and know what happens on overflow
  • Tell constants, mutable variables and shadowing apart
let x = 32;              // type inferred as i32
// x = 16;               // does not compile
let mut y = 16;
y = 10;                  // fine: y is mutable
const MAX_VALUE: u32 = 100_000;

Rust is statically typed, but you rarely write types for local variables: the compiler infers them. An integer literal with nothing else to go on becomes an i32, a signed 32-bit integer.

Immutable by default

Uncommenting x = 16 stops the build with error E0384, cannot assign twice to immutable variable. That is deliberate. When a value cannot change, a reader knows it from the declaration alone, and the compiler can rule out a whole class of bugs — most importantly, two parts of the program changing the same data at once, which is the basis of Rust’s safe concurrency. Mutation is allowed; it just has to be announced with mut.

Constants

const values are always immutable, must have a written type, and must be computable at compile time; they can live outside any function and are conventionally SCREAMING_SNAKE_CASE. Underscores in numeric literals are ignored, so 100_000 is simply one hundred thousand.

Integer types and overflow

Integers come in explicit sizes: i8 to i128 signed, u8 to u128 unsigned, plus isize/usize for sizes and indices. The u32 above holds 0 to 4,294,967,295. Overflow is not silently ignored. An overflow the compiler can see, such as 255u8 + 1, is a compile error; one that depends on run-time values panics in a debug build with attempt to add with overflow, and wraps around (255 + 1 becomes 0) in a release build. When wrapping is intended, say so with wrapping_add, and when overflow is possible, checked_add returns an Option.

Shadowing

The repository stops here, but one more idea completes the picture. A new let with the same name shadows the old binding:

let spaces = "   ";
let spaces = spaces.len();   // a new variable, of a new type (usize)

This is not mutation — spaces was never mut — but a fresh variable that happens to reuse the name. It is the idiomatic way to transform a value through a few steps without inventing names like spaces_str and spaces_num.

Try it yourself. Uncomment x = 16 and read the full compiler message — Rust suggests the fix. Then make let mut s = " "; s = s.len(); compile by replacing mut with shadowing, and explain why the mut version cannot work.

View source on GitHub →