Sub topic 6
Type inference and explicit annotations
This chapter assumes you can write let bindings, know the basic scalar type names (i32, f64, bool, char), and can read a simple compiler error. It covers how Rust decides the type of a binding, when you must state it yourself, and how to read the errors that appear when inference fails.
Static typing without writing every type
Rust is statically typed. Every expression has one type, and the compiler fixes it before the program runs. You still rarely write types on local variables, because the compiler infers them.
fn main() {
let a = 42;
let b = 3.14;
let c = true;
let d = 'x';
let e: u64 = 42;
let f = 42u8;
let g = 1_000_000_i64;
println!("{a} {b} {c} {d} {e} {f} {g}");
println!("{} {} {}", std::mem::size_of_val(&a), std::mem::size_of_val(&b), std::mem::size_of_val(&f));
}The first line prints the values. The second prints 4 8 1, the sizes in bytes of an i32, an f64, and a u8.
Three kinds of information fix a type here:
- A literal with a suffix (
42u8,1_000_000_i64) carries its type. - An annotation (
let e: u64) states the type. - A bare literal (
42,3.14) has no type of its own yet. The compiler looks for other evidence and falls back to a default if it finds none.
How the compiler infers
Rust's inference works on each function body as a whole. It does not read a binding's type from its first line alone. The compiler gives each unknown type a placeholder, then collects constraints from every use of the value and solves for the placeholders. A later line can therefore decide the type of an earlier binding.
fn takes_u64(n: u64) -> u64 {
n * 2
}
fn main() {
let n = 3_000_000_000;
println!("{}", takes_u64(n));
let mut items = Vec::new();
items.push(7u8);
let total: u32 = items.iter().map(|&b| u32::from(b)).sum();
println!("{total}");
}The output is 6000000000 and then 7.
nhas no annotation. Passing it totakes_u64forces it to beu64. Without that call, it would default toi32and the literal would not fit.Vec::new()creates aVec<T>withTunknown. The callitems.push(7u8)settlesTasu8.- The annotation
let total: u32tellssum()which type to produce.
The binding that is declared first and assigned later works the same way. Its type comes from the assignment:
fn main() {
let total;
total = 10u16;
println!("{total}");
}Floating-point literals follow the same process, with f64 as the fallback.
The fallback defaults
| Literal | Default type | Why |
|---|---|---|
| `42` | `i32` | A good general size on most hardware. |
| `3.14` | `f64` | Roughly as fast as `f32` on modern CPUs, with more precision. |
| `true` | `bool` | The only boolean type. |
| `'x'` | `char` | The only character literal type. |
| `"hi"` | `&'static str` | String literals are references to text stored in the program. |
The defaults apply only when nothing else constrains the type. Because of this, the same text can mean different types in different programs:
fn main() {
let x = 2.0;
let y: f32 = x;
println!("{y}");
}Here x is an f32, not an f64, because it is assigned to an f32.
No implicit conversions
Inference picks one type per value. It does not insert conversions between types. Once a binding has a type, it keeps that type everywhere.
fn main() {
let small: u8 = 1;
// let wide: u32 = small;
// error[E0308]: mismatched types: expected `u32`, found `u8`
let wide: u32 = small.into();
println!("{wide}");
}The commented line fails even though every u8 value fits in a u32. Rust requires you to write the conversion, here with .into(). A later chapter covers conversions in detail.
Where you must annotate
Inference stops at item boundaries. Inside a function body, the compiler can solve for types. The signature of the function is a contract that callers and implementers read without looking at the body, so Rust requires it to be explicit.
| Position | Annotation | Reason |
|---|---|---|
| Local `let` binding | Optional when inferable | The body provides the evidence. |
| Function parameters | Required | The signature is the public contract. |
| Function return type | Required unless it is `()` | Same reason. |
| `const` and `static` items | Required | They are items, not statements. |
| Struct and enum fields | Required | Layout must be known from the definition. |
| Closure parameters | Optional | Inferred from the body or first call. |
const MAX_RETRIES: u32 = 3;
struct Reading {
celsius: f64,
valid: bool,
}
fn to_fahrenheit(r: &Reading) -> f64 {
r.celsius * 9.0 / 5.0 + 32.0
}
fn main() {
let r = Reading { celsius: 21.5, valid: true };
println!("{} {} {}", to_fahrenheit(&r), r.valid, MAX_RETRIES);
}This prints 70.7 true 3. Everything at item level is annotated, and nothing inside main is.
Closures: inferred, then fixed
Closure parameters are inferred from how the closure is used, and the compiler then fixes them. A closure is not generic. It has one concrete signature.
fn main() {
let add_one = |n| n + 1;
println!("{}", add_one(5));
// println!("{}", add_one(5.0));
// error[E0308]: mismatched types: expected integer, found floating-point number
}The first call fixes n as an integer, so the second call is rejected. You can annotate a closure when you want the signature to be visible: |n: i64| -> i64 { n + 1 }.
Annotating at the point of use: the turbofish
Sometimes the type belongs to an expression, not a binding. Some functions have a generic parameter that appears only in the return type, so no argument can supply it. parse and collect are common examples. You have two ways to supply the type:
- Annotate the binding:
let m: f64 = "2.5".parse().unwrap(); - Put the type on the call with the turbofish,
::<Type>:"42".parse::<i32>().
fn main() {
let n = "42".parse::<i32>().unwrap();
let m: f64 = "2.5".parse().unwrap();
let words = "a b c".split(' ').collect::<Vec<_>>();
let lens: Vec<usize> = words.iter().map(|w| w.len()).collect();
println!("{n} {m} {words:?} {lens:?}");
}The output is 42 2.5 ["a", "b", "c"] [1, 1, 1].
The _ in Vec<_> is a placeholder. It tells the compiler to infer that part of the type. collect needs to know the container (Vec), and the element type follows from the iterator. Use _ when you want to state only the part the compiler cannot work out. Prefer the turbofish when the expression is part of a longer chain and there is no binding to annotate.
Errors when inference fails
Inference fails in two ways. The constraints may be insufficient, so a type remains unknown. Or they may conflict, so two different types are demanded.
Not enough information
fn main() {
// let v = Vec::new();
// error[E0282]: type annotations needed for `Vec<_>`
// let n = "5".parse().unwrap();
// error: type annotations needed
let v: Vec<i32> = Vec::new();
println!("{}", v.len());
}Neither commented line gives the compiler a way to choose T or the target of parse. The fix is always to add the missing type, either on the binding or with the turbofish. The error message names the exact spot where the type is missing, so read it for the position before reading the suggestion.
Methods on an ambiguous numeric type
A subtler case is calling a method on a literal whose type is not yet fixed. Method lookup needs the concrete type, and the f64 fallback has not been applied at that point.
fn main() {
// let x = 2.0;
// println!("{}", x.powi(2));
// error[E0689]: can't call method `powi` on ambiguous numeric type `{float}`
let x: f64 = 2.0;
println!("{}", x.powi(2));
let y = 2.0_f64;
println!("{}", y.powi(2));
}The program prints 4 twice. Annotate the binding or add a suffix to the literal. The same error appears for integers, such as let n = 10; n.pow(2).
Literals that do not fit
When a literal's type is known, the compiler checks that the value fits.
fn main() {
// let b: u8 = 256;
// error: literal out of range for `u8`
let b: u8 = 255;
println!("{b}");
}This is a deny-by-default lint (overflowing_literals), so it stops compilation. The same literal with no other constraint would default to i32, which holds up to 2,147,483,647. A literal above that with no other evidence fails the same way. If you meant a larger type, annotate it, as in let big: i64 = 3_000_000_000;.
Conflicting constraints
If two uses demand different types, you get E0308 (mismatched types). The error often points at the second use, but the first use is just as responsible. When the message seems to blame the wrong line, add an annotation to the binding. That tells the compiler which use is right and moves the error to the one that is wrong.
When to annotate
Inference works well, so choose annotations by purpose, not habit.
- Annotate when the type is a decision. Use a specific width when it matters to the program:
u8for a byte,u64for a counter that can pass four billion,usizefor indexes and lengths. The defaulti32is a convenience, not a design. - Annotate to get an error in the right place. If you write
let count: u32 = items.len();, the compiler reports the mismatch withusizeon that line, not several lines later. - Annotate to document. A reader skimming
let timeout: Duration = parse_config(...)learns the type without opening the function. - Skip annotations when the type is obvious.
let name = String::new();andlet n = items.len();say nothing more with a type attached. Rust style generally leaves them off. - Use
_for partial annotation.Vec<_>andHashMap<String, _>constrain what you care about and leave the rest.
Summary of the working model
- Inference is local to a function body and uses every use of a value, including uses that come after the declaration.
- Unsuffixed numeric literals default to
i32andf64only when nothing else decides. - Items (function signatures, constants, statics, fields) need explicit types.
- Types never convert on their own. Inference chooses one type, and you convert explicitly.
- Fix a failure by adding the smallest annotation that resolves it: a suffix, a binding annotation, a
_placeholder, or a turbofish.
Exercise
State the type the compiler infers for each binding, then say what happens if you add the line let e = a.pow(2); after them.
let a = 7;
let b = 7.0;
let c: u8 = 7;
let d = c + 1;
Show answer
a is i32 (integer fallback), b is f64 (float fallback), c is u8 (annotated), and d is u8 (adding the literal 1 to a u8 makes the literal a u8). The line let e = a.pow(2); fails to compile with error E0689, "can't call method pow on ambiguous numeric type {integer}". At the point of the method call, a has not yet received its i32 fallback. Writing let a: i32 = 7; or let a = 7_i32; fixes it.
Exercise
Why does let n = "5".parse().unwrap(); fail to compile, and give two different ways to fix it so that n is a u16.
Show answer
parse is generic over its return type, and nothing in the program says which type n should have, so the compiler reports that type annotations are needed. Fix 1: annotate the binding, let n: u16 = "5".parse().unwrap();. Fix 2: use the turbofish, let n = "5".parse::<u16>().unwrap();. A later use that requires a u16, such as passing n to a function that takes a u16, would also fix the type.