Rust Variables and Data Types
Learn Rust variables, immutability, shadowing, and the scalar and compound data types you will use every day.
Second post in the basic Rust series. Rust puts unusual care into how you declare and use variables — the rules here power its safety guarantees.
Variables are immutable by default#
let name = "Ada";
name = "Grace"; // error: cannot assign twice to immutable variablerustThis is deliberate: immutable data is easy to reason about and safe to share. Make a variable mutable with mut:
let mut score = 10;
score += 5;rustUse mut only when you actually need it.
Type inference#
Rust infers types, but you can annotate them:
let count: u32 = 42;
let ratio: f64 = 3.14;
let name: &str = "Rust";
let done: bool = true;rustScalar types#
| Type | Values |
|---|---|
| Integers | i8..i128, u8..u128 (signed/unsigned) |
| Floats | f32, f64 |
| Booleans | bool |
| Characters | char (Unicode, 4 bytes) |
Default integer type is i32; default float is f64:
let x = 5; // i32
let y = 2.5; // f64rustCompound types#
Tuples group values of any types:
let point = (3, 5);
let (x, y) = point; // destructuring
println!("{}", point.0); // 3rustArrays hold several values of the same type with fixed length:
let primes = [2, 3, 5, 7, 11];
println!("{}", primes[0]); // 2rustConstants#
const values are always immutable and must have a known type:
const MAX_SPEED: u32 = 120;rustUnlike let, const can be declared at any scope and is inlined at compile time.
Shadowing#
You can reuse a variable name to transform its value, keeping the old value until the new one takes effect:
let x = 5;
let x = x + 1;rustShadowing lets you change type too:
let label = "12"; // &str
let label = label.len(); // usizerustConclusion#
Rust’s variable rules — immutability by default, explicit mut, shadowing — make data flow predictable. Next in this series: control flow.