Rust Error E0282 Type Annotations Needed and How to Add Them
E0282 means the compiler cannot work out a type from context. Add a turbofish, a let annotation or a typed collect and it goes away.

error[E0282]: type annotations needed means the compiler followed every clue it had and still could not decide a type. Rust infers types from how values are used, and it will deduce an astonishing amount, but some calls are generic over their output: Vec::new() could hold anything, parse() could produce any parsable type, collect() could build any collection. If nothing later in the function pins the type down, the compiler stops and asks you. The fix is always one of three moves, a type annotation on the variable, a turbofish on the call, or a clue elsewhere in the code. This post shows the five calls that cause nearly every one of these errors, with the real messages from Rust 1.99, and the repair for each.
A note on the number: depending on which part of the inference fails, the compiler reports E0282, E0283, E0284 or E0790. They share one cause and one fix, and you will see all four below.
An empty container
The commonest form is a collection with nothing in it yet:
fn main() {
let items = Vec::new();
println!("{}", items.len());
}error[E0282]: type annotations needed for `Vec<_>`
--> a282.rs:2:9
|
2 | let items = Vec::new();
| ^^^^^ ---------- type must be known at this point
|
help: consider giving `items` an explicit type, where the type for type parameter `T` is specified
|
2 | let items: Vec<T> = Vec::new();
| ++++++++Vec::new() returns a Vec<T> for some T, and calling .len() does not say what T is. The size of the vector is known, but the element type is not, and the compiler needs it to lay out memory. Notice what would have fixed it for free: a single later line such as items.push(1u32) fixes T to u32, and the error disappears. If the type really is determined by later code, you can leave the annotation off. When the vector might stay empty, or the pushes are in a branch the compiler cannot connect, give the type: let items: Vec<u32> = Vec::new();, or move the information to the call with Vec::<u32>::new().
parse without a target
fn main() {
let n = "42".parse().unwrap();
println!("{}", n);
}error[E0284]: type annotations needed
--> b282.rs:2:9
|
2 | let n = "42".parse().unwrap();
| ^ ----- type must be known at this point
|
= note: cannot satisfy `<_ as FromStr>::Err == _`
= note: the type must also implement `FromStr`
help: consider giving `n` an explicit type
|
2 | let n: /* Type */ = "42".parse().unwrap();
| ++++++++++++str::parse<F> converts a string into any type F that implements FromStr: integers, floats, bool, IP addresses, your own types. println!("{}", n) works for all of them, so nothing narrows the choice. Say which: let n: u32 = ... or "42".parse::<u32>(). The turbofish, ::<Type>, is the way to give a generic argument directly on a call, and it is what you use when the result feeds straight into an expression with no variable to annotate.
collect without a destination
fn main() {
let words = "a b c".split(' ').collect();
println!("{:?}", words);
}error[E0283]: type annotations needed
--> c282.rs:2:9
|
2 | let words = "a b c".split(' ').collect();
| ^^^^^ ------- type must be known at this point
|
= note: the type must implement `FromIterator<&str>`
help: consider giving `words` an explicit type
|
2 | let words: Vec<_> = "a b c".split(' ').collect();
| ++++++++collect is the most generic call in everyday Rust. The same iterator can become a Vec, a HashSet, a BTreeSet, a String, a HashMap (of pairs), or a Result<Vec<_>, _>, and the compiler will not choose for you. The suggestion Vec<_> is the usual answer; the underscore means "infer the element type, I only care about the container". The turbofish form reads well in a chain: .collect::<Vec<_>>(). This is also the entry point for a neat trick: collecting an iterator of Result<T, E> into Result<Vec<T>, E> stops at the first error, which is why the container type matters.
sum and product
fn main() {
let total = [1, 2, 3].iter().sum();
println!("{}", total);
}error[E0283]: type annotations needed
--> d282.rs:2:9
|
2 | let total = [1, 2, 3].iter().sum();
| ^^^^^ --- type must be known at this point
|
= note: the type must implement `Sum<&i32>`
= help: the following types implement trait `Sum<A>`:
`Duration` implements `Sum<&'a Duration>`
`Duration` implements `Sum`
`Option<T>` implements `Sum<Option<U>>`
`Result<T, E>` implements `Sum<Result<U, E>>`
and 88 othersIterator::sum is generic over the result type, and the standard library implements Sum for dozens of types. Summing integers is only one. Annotate the variable, let total: i32 = ..., or use the turbofish sum::<i32>(). The error lists candidate types and says "and 88 others", which is the compiler admitting there is no reasonable default. Floats, Duration, Option<T> and Result<T, E> all qualify, so the choice has to be yours.
Default::default() with no target
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> e282.rs:2:18
|
2 | let result = Default::default();
| ^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation
|
2 | let result = </* self type */ as Default>::default();
| +++++++++++++++++++ +Calling a trait's function without saying which type's implementation you want is the extreme case: there is nothing to infer from. Name the type through an annotation (let zero: u8 = Default::default();) or call it on the type (String::default()). The fully qualified syntax in the suggestion, <Type as Trait>::function(), is the general tool when two traits have a method with the same name.
All five, repaired
fn main() {
// 1. A container with no elements: say what it will hold.
let items: Vec<u32> = Vec::new();
let more = Vec::<String>::with_capacity(4); // turbofish: the type goes on the call
println!("{} {}", items.len(), more.capacity());
// 2. parse() could produce any FromStr type: pick one.
let n: u32 = "42".parse().unwrap();
let m = "7".parse::<i64>().unwrap();
println!("{n} {m}");
// 3. collect() could build many collections.
let words: Vec<&str> = "a b c".split(' ').collect();
let unique = "a b a".split(' ').collect::<std::collections::BTreeSet<_>>();
println!("{words:?} {unique:?}");
// 4. sum() and product() are generic over the result.
let total: i32 = [1, 2, 3].iter().sum();
let product = [2, 3, 4].iter().product::<u64>();
println!("{total} {product}");
// 5. Default::default() needs a target.
let zero: u8 = Default::default();
let empty = String::default();
println!("{zero} {empty:?}");
}0 4
42 7
["a", "b", "c"] {"a", "b"}
6 24
0 ""Each section picks the style that reads best at that spot. An annotation on the let suits a variable that is used several times. A turbofish suits a call whose result flows into another expression. The Vec::<String>::with_capacity(4) form puts the type on the constructor, and the printed capacity of 4 confirms the vector was created for strings.
Closure parameters
A closure parameter is inferred from how the closure is used, and the compiler reads the body from top to bottom. If the first thing the body does is call a method on a parameter whose type is not yet known, inference has nothing to go on:
fn main() {
let describe = |item| format!("item: {}", item.len());
println!("{}", describe("abc"));
}error[E0282]: type annotations needed
--> l282.rs:2:21
|
2 | let describe = |item| format!("item: {}", item.len());
| ^^^^ ---- type must be known at this point
|
help: consider giving this closure parameter an explicit type
|
2 | let describe = |item: /* Type */| format!("item: {}", item.len());
| ++++++++++++The call describe("abc") comes after the closure body, and the compiler needs the type of item at the .len() inside it. Annotate the parameter, |item: &str|, and the body type-checks. Closures passed directly to a function such as .map(|x| x.len()) do not hit this, because the function's signature supplies the parameter type, which is one reason iterator chains rarely need annotations.
Choosing where to put the type
Put the annotation where it documents the code best. For a struct field or a function signature, the type is already written, so inference flows from there and the error cannot happen. For a local variable whose meaning is not obvious from the right-hand side, annotate the variable: let timeout: Duration = ... tells the reader what it is. For a chained call in the middle of an expression, use the turbofish. For collect, remember the underscore: Vec<_> specifies the container and leaves the element type to inference, so you do not have to write Vec<&str> by hand.
Two habits reduce these errors. Write the types of function signatures in full, always, because the compiler checks the body against them and most inference then has an anchor. And when an error mentions a type you did not expect, such as {integer} or _, read it as "the compiler has not decided yet", and look for the variable that should carry the decision. For the neighboring errors, E0308 is a type that was decided and is wrong, and E0277 is a decided type that lacks a trait.
When you are unsure which annotation to write, let the compiler tell you what it inferred for the nearest variable that does work, then copy that type. Hovering a variable in rust-analyzer shows it, and writing let () = value; is an old trick that makes the compiler print the actual type in its mismatch error. Either way, the annotation is cheap, and it also documents the code for the next reader.


