Sub topic 6
Type inference and explicit annotations
This chapter assumes you can declare variables with let, know the difference between let and let mut, and can read simple compiler errors. It covers how Rust decides the type of a binding, and when you must write the type yourself.
Rust is statically typed, not explicitly typed
Every value in Rust has one type, and the compiler knows it at compile time. You do not have to write that type everywhere. The compiler infers it from the value and from how the binding is used later.
fn main() {
let count = 10;
let ratio = 0.5;
let letter = 'r';
let ready = true;
println!("{count} {ratio} {letter} {ready}");
}Here the compiler picks i32, f64, char, and bool. The integer and float choices are defaults. An integer literal with no other constraint becomes i32. A float literal becomes f64.
Inference looks at later code
Inference is not limited to the right-hand side of the let. The compiler uses every later use of the binding to settle the type.
fn main() {
let mut values = Vec::new();
values.push(7u8);
let first = values[0];
println!("{first}");
}At the Vec::new() call the element type is unknown. The push(7u8) call fixes it as Vec<u8>. If a type is still unresolved at the end of the function, the compiler reports an error instead of guessing.
A literal's type can also come from how it is used:
fn double(n: u64) -> u64 {
n * 2
}
fn main() {
let n = 21;
println!("{}", double(n));
}n is not i32 here. Passing it to a function that takes u64 makes the compiler infer u64.
Writing an annotation
A type annotation goes after the name, separated by a colon.
fn main() {
let small: u8 = 200;
let precise: f32 = 3.14;
let items: [i32; 3] = [1, 2, 3];
println!("{small} {precise} {:?}", items);
}You can also put the type on a literal with a suffix, such as 200u8 or 3.14f32. Both forms mean the same thing. Use whichever is clearer at that spot.
When an annotation is required
Function signatures always need explicit types for parameters and return values. Rust does not infer them across function boundaries. Inside a function body, annotations are needed only when the compiler has more than one valid choice.
The most common case is parse, which can produce many types:
fn main() {
let guess = "42".parse().unwrap();
println!("{guess}");
}This fails with error[E0284]: type annotations needed, because parse could return any type that implements FromStr. Either of these fixes it:
fn main() {
let a: u32 = "42".parse().unwrap();
let b = "42".parse::<u32>().unwrap();
println!("{a} {b}");
}The second form is called the turbofish, ::<Type>. It supplies the type argument directly to the function. Another common case is collect, which can build many collection types:
fn main() {
let doubled: Vec<i32> = (1..=3).map(|n| n * 2).collect();
println!("{:?}", doubled);
}How the compiler reasons
The following diagram shows the order in which the compiler settles a binding's type.
Common errors
- Mismatched types.
let x: u8 = 300;fails because the value does not fit. For literals, the compiler rejects out-of-range values with a deny-by-defaultoverflowing_literalslint. - Conflicting uses. If you pass the same inferred integer to a function expecting
u32and another expectingu64, one call fails. The binding has only one type. Convert at one of the call sites. - Changing type by assignment.
let mut n = 5; n = "five";fails. Inference fixes the type once. To change the type, use shadowing with a newlet. - Surprising defaults. An unconstrained literal becomes
i32. If you expect a larger range, annotate the type.
Exercise
The line let total = "10".parse().unwrap(); fails to compile. Give two different ways to fix it so that total is a u16.
Show answer
Annotate the binding: let total: u16 = "10".parse().unwrap();. Or use the turbofish: let total = "10".parse::<u16>().unwrap();. Both tell parse which type to produce.
Exercise
In let mut v = Vec::new(); v.push(1);, what is the type of v, and why?
Show answer
Vec<i32>. Vec::new() leaves the element type open. The literal 1 has no other constraint, so it takes the default integer type i32.