Values with a known shape
Every value in a Rust program has a type that the compiler knows before the program runs: this is a 32-bit signed integer, that is a pair of floating-point numbers, this other thing is a single Unicode character. The compiler uses that knowledge to reject nonsense (adding a word to a number), to choose the right machine instructions, and to lay values out in memory with no wasted space and no hidden bookkeeping.
If you come from Python or JavaScript, two things will feel different at first. Variables are immutable by default: once a value is bound to a name, it stays put unless you explicitly ask for permission to change it. And numbers come in many sizes, from an 8-bit byte to a 128-bit integer, because systems programmers care how many bytes a value takes, what happens when it gets too big, and what the hardware does with it.
Neither is bureaucracy for its own sake. Immutability by default means that when you read let total = ..., you know total never changes further down, which makes long functions much easier to reason about. Explicit sizes mean a network packet, a pixel or a file offset has exactly the representation you intended. And because the compiler infers most types from context, you write far fewer annotations than you might fear.
Variables, mutability and shadowing
Definition— binding
let name = value; creates a binding: it gives a value a name. The binding is immutable unless declared with let mut. You may add a type annotation, let name: Type = value;, when the compiler cannot infer one or when you want to be explicit.
fn main() {
let guests = 4;
// guests = 5; // error: cannot assign twice to immutable variable
let mut cups_of_tea = 0;
cups_of_tea += guests;
cups_of_tea += 1; // one for the host
println!("{guests} guests, {cups_of_tea} cups of tea");
// Shadowing: a new variable with the same name, possibly a new type.
let reply = " 42 ";
let reply = reply.trim();
let reply: i32 = reply.parse().unwrap();
println!("the reply plus one is {}", reply + 1);
const SECONDS_PER_DAY: u32 = 24 * 60 * 60;
println!("a day has {SECONDS_PER_DAY} seconds");
}4 guests, 5 cups of tea
the reply plus one is 43
a day has 86400 secondsThree ideas are packed in here.
mut gives permission to change a binding. If you uncomment the second line, the compiler refuses with "cannot assign twice to immutable variable", and suggests adding mut. The rustc warning for the opposite case (a mut variable that is never changed) is just as useful: it tells you a variable is simpler than you declared.
Shadowing declares a new variable with the same name as an old one. The three reply lines are three different variables: a string with spaces, a trimmed string slice, and an integer. Shadowing is idiomatic when you transform a value step by step and never need the earlier form again; it saves inventing names like reply_str and reply_num. It is not mutation: the old value is simply no longer reachable by that name, and each new binding can have a different type, which mut cannot do.
const declares a compile-time constant. Its type must always be written, its value must be computable while compiling, and by convention its name is in SCREAMING_SNAKE_CASE. Constants can live outside any function, which is where they usually go. A related item, static, is a single value with a fixed address in memory for the whole run of the program; you will meet it rarely, mainly for global tables and in low-level code.
(parse().unwrap() turns text into a number and stops the program if the text isn't one. Lesson 8 replaces unwrap with proper error handling.)
Numbers, truth values and characters
Rust's scalar types hold a single value:
| Type | Meaning | Range or notes |
|---|---|---|
i8, i16, i32, i64, i128 | signed integers of 8 to 128 bits | i32: −2,147,483,648 to 2,147,483,647 |
u8, u16, u32, u64, u128 | unsigned integers | u8: 0 to 255 |
isize, usize | integers the size of a pointer (64 bits on most machines) | usize is the type of indexes and lengths |
f32, f64 | IEEE 754 floating point, single and double precision | f64 is the default |
bool | true or false | one byte |
char | one Unicode scalar value | four bytes: 'a', 'ß', '中', '🦀' |
When nothing else constrains an integer literal, Rust chooses i32; for a float literal, f64. Literals can carry underscores for readability (1_000_000), a type suffix (255_u8, 2_f64), and a base prefix (0xff, 0o17, 0b1010). b'A' is the byte 65, of type u8.
How much do you have to write?
Less than you might expect. Rust's type inference works across a whole function body: it looks at how a variable is used later, not only at how it starts. If you write let mut count = 0; and later pass count to a function that takes a u64, then count is a u64 from the start. Annotations are needed in three places: function signatures (always, by design, so that each function's contract is readable on its own), constants and statics, and the occasional spot where the compiler has two equally good choices, such as "42".parse(), which could produce any number type until you say which.
Which integer type should you pick? Use i32 or i64 for ordinary counts and arithmetic that may go negative, u8 for raw bytes, usize for anything that indexes or measures a collection (the standard library insists on it), and fixed sizes like u16 or u32 when a file format or protocol dictates them. Reach for u32 "because the value is never negative" with care: subtracting two unsigned numbers whose difference would be negative overflows, which is exactly the bug you were trying to avoid.
Overflow is a decision, not an accident
What should 250_u8 + 10 be? It does not fit in a byte. Rust's answer depends on the build: in a debug build, arithmetic overflow panics (stops the program with a message), because it is almost always a bug; in a release build, the checks are off by default for speed and the value wraps around modulo 2⁸. Here is a debug build of a program that adds 10 to a u8 holding 250:
thread 'main' (2233536) panicked at ov.rs:3:19:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace(The number in parentheses identifies the thread and changes from run to run.) When overflow is possible and meaningful, don't leave it to the build mode: say what you want with one of the method families every integer type has.
fn main() {
let big: i32 = i32::MAX;
println!("i32 runs from {} to {}", i32::MIN, big);
println!("u8 runs from {} to {}", u8::MIN, u8::MAX);
let a: u8 = 250;
println!("checked: {:?}", a.checked_add(10));
println!("checked: {:?}", a.checked_add(5));
println!("wrapping: {}", a.wrapping_add(10));
println!("saturating: {}", a.saturating_add(10));
println!("overflowing:{:?}", a.overflowing_add(10));
let population: u64 = 1_428_627_663;
let as_small = population as u16; // keeps only the low 16 bits
println!("{population} as u16 is {as_small}");
let fits = u16::try_from(60_000_u64);
let too_big = u16::try_from(population);
println!("{fits:?}");
println!("{too_big:?}");
let widened: u64 = u64::from(a); // lossless, so From exists
println!("{widened}");
}i32 runs from -2147483648 to 2147483647
u8 runs from 0 to 255
checked: None
checked: Some(255)
wrapping: 4
saturating: 255
overflowing:(4, true)
1428627663 as u16 is 8399
Ok(60000)
Err(TryFromIntError(()))
250checked_addreturns anOption:Some(result)if it fits,Noneif not. Use it when overflow means "this input is invalid".wrapping_addwraps modulo 2ⁿ. Use it for hashes, checksums and ring counters, where wrapping is the intended maths.saturating_addclamps at the type's maximum or minimum. Use it for things like volume levels and progress bars.overflowing_addgives the wrapped value and a flag saying whether it wrapped.
The same families exist for subtraction, multiplication, negation, shifts and powers (checked_mul, saturating_sub, wrapping_pow and so on).
Converting between numeric types
Rust never converts numbers silently, even from u8 to u64. You choose a conversion:
u64::from(a)(ora.into()) exists only when every value fits, so it can never lose information.u16::try_from(x)checks at run time and returnsOk(value)orErr(...).x as u16always succeeds, by force: it keeps the low bits of an integer, truncates floats toward zero, and clamps floats that are out of range. Above, the population of a large country becomes 8399.asis fine for conversions you know are safe (ani32you just checked is non-negative into ausize), but in new code preferfromandtry_from, which say what you mean and can't lose data quietly.
Integer and floating-point arithmetic
fn main() {
println!("{}", 7 / 2);
println!("{}", -7 / 2);
println!("{}", -7 % 2);
println!("{}", (-7_i32).rem_euclid(2));
println!("{}", 7.0 / 2.0);
println!("{}", 0.1 + 0.2);
println!("{}", 0.1 + 0.2 == 0.3);
println!("{}", (0.1_f64 + 0.2 - 0.3).abs() < 1e-9);
let x = f64::NAN;
let y = x;
println!("{}", x == y);
println!("{}", 1.0_f64 / 0.0);
println!("{}", 2_f64.sqrt());
println!("{}", 2_i32.pow(10));
}3
-3
-1
1
3.5
0.30000000000000004
false
true
false
inf
1.4142135623730951
1024Integer division truncates toward zero, so -7 / 2 is −3 and the remainder % takes the sign of the left operand. When you need a remainder that is never negative (to wrap an index around a circular buffer, say), use rem_euclid. Floating-point numbers follow IEEE 754 exactly as in every other mainstream language: 0.1 + 0.2 is not exactly 0.3, so compare floats with a tolerance; dividing by zero gives infinity rather than a panic; and NaN ("not a number") is not equal even to itself. Integer division by zero, on the other hand, always panics.
Tuples, arrays and functions
Two compound types are built into the language. A tuple groups a fixed number of values of possibly different types: (i32, f64, char). An array holds a fixed number of values of the same type, written [T; N]: [i32; 5] is five integers. Both live directly where they are declared (on the stack, inside a struct) with no separate allocation. For a list that can grow, you will use Vec<T> from lesson 7.
fn min_max(values: [i32; 5]) -> (i32, i32) {
let mut lo = values[0];
let mut hi = values[0];
for v in values {
if v < lo {
lo = v;
}
if v > hi {
hi = v;
}
}
(lo, hi)
}
fn main() {
let temperatures = [12, -4, 31, 7, 18];
let (coldest, hottest) = min_max(temperatures);
println!("range: {coldest} to {hottest}");
let point: (f64, f64) = (3.0, 4.0);
let distance = {
let (x, y) = point;
(x * x + y * y).sqrt()
};
println!("distance from origin: {distance}");
println!("first element: {}, length: {}", temperatures[0], temperatures.len());
let letter = 'ß';
let emoji = '🦀';
println!("{letter} is {} bytes in UTF-8, {emoji} is {}", letter.len_utf8(), emoji.len_utf8());
let nothing = ();
println!("{nothing:?}");
}range: -4 to 31
distance from origin: 5
first element: 12, length: 5
ß is 2 bytes in UTF-8, 🦀 is 4
()Points worth slowing down for:
min_maxreturns two values at once by returning a tuple, andlet (coldest, hottest) = ...takes it apart. This destructuring is a pattern, the topic of the next lesson.- Indexing with
temperatures[0]is checked: an index past the end panics instead of reading whatever happens to be in memory. Lengths and indexes areusize. - The type annotation on
pointmatters. Without it the compiler knows only "some float" when it reaches.sqrt()and asks you to choose (error E0689); with it, everything isf64. (), the empty tuple, is called unit. It is the value of expressions that produce nothing interesting, and the return type of functions that don't declare one, likemain.
Expressions, statements and the meaningful semicolon
Most things in Rust are expressions: they produce a value. 2 + 3 is an expression, so is a function call, so is an if, and so is a block in braces, whose value is the value of its last expression. That is how distance above is computed: the block introduces temporary names x and y, and its final line, with no semicolon, is its value. When the block ends, x and y go away, so they cannot leak into the rest of main.
A statement does something but has no useful value. let is a statement, and adding a semicolon turns any expression into a statement whose value is thrown away. That is why the semicolon is not decoration in Rust. Look what happens if you add one to the last line of a function:
fn add(a: i32, b: i32) -> i32 {
a + b;
}error[E0308]: mismatched types
--> e3.rs:1:27
|
1 | fn add(a: i32, b: i32) -> i32 {
| --- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | a + b;
| - help: remove this semicolon to return this valueThe body now ends in a statement, so the block's value is (), which isn't the promised i32. The compiler explains this and points at the semicolon. The style experienced Rust programmers use is: the final expression without a semicolon for the normal result, and return only for leaving a function early.
Analogy, not a formal construction
Think of a block as a small kitchen with a serving hatch. Everything you prepare inside (the temporary bindings) stays in the kitchen; only the dish you put in the hatch at the end (the final expression) goes out. A semicolon on that last line is like washing the dish instead of serving it.
Common misconceptions
Misconception
"Shadowing is the same as mut." Shadowing creates a new variable, which may have a different type, and leaves the old value untouched (code that borrowed it still sees it). mut changes the value stored in one variable, which must keep its type. Use shadowing for a chain of transformations, mut for a value that genuinely changes over time, like a counter.
Misconception
"Integer overflow always panics in Rust." Only when overflow checks are on, which by default means debug builds. In release builds it wraps unless you enable overflow-checks in the build profile. Code that must behave the same in both says so explicitly with checked_, wrapping_ or saturating_ methods.
Misconception
"as is a safe cast because Rust is a safe language." as cannot cause undefined behaviour, but it can change your number: 300_i32 as u8 is 44 and -1_i32 as u8 is 255, with no warning. Prefer From for widening and TryFrom when the value might not fit.
Misconception
"A char is a byte." A char is a Unicode scalar value and always takes four bytes in memory; inside a UTF-8 string, one character takes one to four bytes. Lesson 4 shows why you can't index a string by position.
Exercises
Predict first, then run the code to check yourself.
1. Values, mutability and types
Warm-upComputationalWhat does this program print? Write the two lines separated by a space.
fn main() {
let x = 5;
let x = x * 2;
{
let x = x + 1;
println!("{x}");
}
println!("{x}");
}
2. Values, mutability and types
CoreComputationalWhat does println!("{} {}", 300_i32 as u8, -1_i32 as u8); print?
3. Values, mutability and types
CoreComputationalWhat does println!("{} {}", -17 / 5, -17 % 5); print?
4. Values, mutability and types
CoreComputationalLet a = 200_u8.saturating_add(100) and b = 200_u8.wrapping_add(100). What is a + b as an ordinary integer (do the final addition on paper, not in u8)?
5. Values, mutability and types
CoreComputationalWhich of these lines compile? Choose all that apply (assume each is inside fn main).
6. Values, mutability and types
StretchHumanThis function does not compile:
fn area(w: u32, h: u32) -> u32 {
w * h;
}
What is the best explanation?
Further reading and resources
- The Rust Programming Language, chapter 3: Common Programming Concepts · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The Rust Reference: Types
- Primitive type i32, in the standard library documentationEvery integer method (checked_add, wrapping_mul, pow, rem_euclid and many more) with examples.
- The Rust Reference: Statements and expressions