Syntax and Basics
Core Rust syntax you reach for in every file. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Core Rust syntax you reach for in every file. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Bindings are immutable by default; mut allows reassignment.
let mut x = 5;
x = 6;
x // 6The compiler infers types; annotate when needed for clarity or ambiguity.
let n = 42; // i32 by default for integers
let f: f64 = 2.5;
n + 1 // 43Re-declare a name with let to transform type or value without mut.
let s = "42";
let s: i32 = s.parse().unwrap();
s // 42if is an expression - branches must match types when used as a value.
let n = 7;
let label = if n > 5 { "big" } else { "small" };
label // "big"Exhaustive pattern matching on enums and other types.
let x = 2;
match x {
1 => "one",
2 => "two",
_ => "other",
} // "two"loop can return a value via break expr.
let mut n = 0;
let v = loop {
n += 1;
if n == 3 { break n * 10; }
};
v // 30while for conditions; for iterates ranges and collections.
let mut sum = 0;
for i in 1..=3 {
sum += i;
}
sum // 6Last expression without semicolon is the return value.
fn add(a: i32, b: i32) -> i32 {
a + b
}
add(2, 3) // 5Group values in tuples; destructure with let.
let t = (1, "a");
let (n, s) = t;
n // 1
// s == "a"Fixed-size arrays; slices borrow a view into contiguous data.
let a = [10, 20, 30];
let s = &a[1..];
s[0] // 20
a.len() // 3Compile-time constants vs long-lived statics.
const MAX: u32 = 100;
MAX // 100
// static GLOBAL: i32 = 1; // 'static lifetimeprintln! uses {} Display and {:?} Debug.
let name = "Ada";
// println!("hi {name}"); // hi Ada
format!("hi {name}") // "hi Ada"Numeric casts use as carefully (truncation possible).
let n: f64 = 3.9;
n as i32 // 3Blocks evaluate to their last expression.
let x = {
let y = 2;
y + 1
};
x // 3Functions with no return value return () the unit type.
fn log_hi() {
let _ = "hi";
}
log_hi(); // ()Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Reviewed by Chris St. John·Last updated Jul 19, 2026