blog.dopana

Back

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 variable
rust

This 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;
rust

Use 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;
rust

Scalar types#

TypeValues
Integersi8..i128, u8..u128 (signed/unsigned)
Floatsf32, f64
Booleansbool
Characterschar (Unicode, 4 bytes)

Default integer type is i32; default float is f64:

let x = 5;       // i32
let y = 2.5;     // f64
rust

Compound types#

Tuples group values of any types:

let point = (3, 5);
let (x, y) = point;   // destructuring
println!("{}", point.0);   // 3
rust

Arrays hold several values of the same type with fixed length:

let primes = [2, 3, 5, 7, 11];
println!("{}", primes[0]);   // 2
rust

Constants#

const values are always immutable and must have a known type:

const MAX_SPEED: u32 = 120;
rust

Unlike 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;
rust

Shadowing lets you change type too:

let label = "12";      // &str
let label = label.len();   // usize
rust

Conclusion#

Rust’s variable rules — immutability by default, explicit mut, shadowing — make data flow predictable. Next in this series: control flow.

References#