Rust E0282: type annotations needed
E0282 means inference ran out of information. Annotate the binding, add a turbofish to collect or parse, or fix the signature the value flows into.

Introduction & Quick Summary
The code looks complete and rustc stops with a note that points at a variable rather than at a mistake:
error[E0282]: type annotations needed
--> src/main.rs:4:20
|
4 | let totals = rows.iter().map(|r| r.amount).collect();
| ^^^^^^^ cannot infer typeQuick answer: collect() can build many container types, and nothing in this statement says which one. Annotate the binding, or use a turbofish on the method:
let totals: Vec<i64> = rows.iter().map(|r| r.amount).collect();
// or
let totals = rows.iter().map(|r| r.amount).collect::<Vec<i64>>();E0282 is the compiler saying that inference reached the end of the function without enough information, not that the code is wrong. The fix is always to supply the missing type at the point where the chain is consumed — a variable annotation, a turbofish, a return type, or a type that a later use would have provided. This guide covers the six inference sites that produce it most often, how to tell E0282 from E0283 and E0284, and the patterns where the annotation should replace a design guess.
Core Mechanics, Signatures & Reproducible Setup
Rust infers types from uses: the initializer, later method calls, the function's return type, and the trait bounds in scope. E0282 means no use constrained the type variable to a single concrete type.
fn main() {
let n = "42".parse().unwrap(); // E0282: parse can produce any FromStr type
println!("{}", n + 1); // this line would have fixed it, but the
} // error is reported at the parse siteThree related errors differ in what is missing:
- E0282 — no type could be inferred at all.
- E0283 — several types match and the compiler will not choose (
type annotations needed: cannot resolve 'num::Zero'). - E0284 — inference depended on itself, usually through a generic bound that mentions the type being inferred.
A reproducible file with the three common sites:
cargo new infer && cd infer
cat > src/main.rs <<'RS'
use std::collections::HashMap;
fn main() {
let parsed = "42".parse().unwrap(); // E0282
let items = vec![1, 2, 3].into_iter().map(|x| x * 2).collect(); // E0282
let mut map = HashMap::new();
map.insert("a", 1); // ok: fixed by the value
let value = map.get("a").copied().unwrap_or_default(); // E0282 if unused later
println!("{parsed} {items:?} {value}");
}
RS
cargo buildInference flows forward from the initializer and backward from uses, so an unused binding can be ambiguous while the same code compiles once a use pins the type. That is why removing a println! during a refactor sometimes "breaks" compilation.
Key Comparison Table
| Site | Ambiguous because | Annotation |
|---|---|---|
.collect() | many FromIterator impls | let v: Vec<T> = … or ::<Vec<T>>() |
.parse() | any FromStr type | ::<i32>() or a typed binding |
.into() / From::from | many target impls | typed binding or ::<Target>() |
empty Vec::new(), HashMap::new() | no elements to infer from | Vec::<u8>::new() |
closure returning Default::default() | the return type is free | annotate the closure or the binding |
? on a generic Result | error type conversion is open | annotate or map_err |
| Error | What it means | Typical fix |
|---|---|---|
| E0282 | cannot infer at all | add an annotation |
| E0283 | multiple candidate impls | turbofish on the method |
| E0284 | self-referential inference | break the generic cycle with a concrete type |
| E0277 | trait bound not satisfied | the type is known, the bound is not met |
| E0308 | mismatched types | the type is known and wrong |
| Fix style | Example | Best when |
|---|---|---|
| binding annotation | let v: Vec<String> = … | the variable is used later |
| turbofish | collect::<Vec<String>>() | the value is passed inline |
| function signature | fn f() -> Result<(), Error> | the function owns the type |
| explicit struct field type | struct S { items: Vec<u8> } | the type belongs to the data model |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. collect() into the type you actually need
The container type is a design decision, so state it. If a later function takes &[T], collecting into Vec<T> and borrowing is usually right; if the value is returned, the function's return type fixes it:
fn totals(rows: &[Row]) -> Vec<i64> {
rows.iter().map(|r| r.amount).collect() // return type pins Vec<i64>
}
fn lookup(rows: &[Row]) -> HashMap<String, i64> {
rows.iter().map(|r| (r.id.clone(), r.amount)).collect() // key/value infer from the map type
}collect() into Result<Vec<_>, _> is the neat way to stop at the first error:
let numbers: Result<Vec<i32>, _> = ["1", "2", "x"].iter().map(|s| s.parse::<i32>()).collect();2. parse() and FromStr
parse returns Result<F, F::Err> for any F: FromStr, so the turbofish belongs on parse, not on unwrap:
let port = "8080".parse::<u16>().expect("port");
let ratio = "0.5".parse::<f64>()?;
// when the error type matters, annotate the whole binding
let count: u32 = input.parse().map_err(|_| Error::BadCount)?;unwrap() and expect() do not help inference because their type parameter is already tied to the Result being unwrapped.
3. ?, into(), and error conversion
The ? operator converts the error with From, which is exactly the open-ended part that E0282 complains about. Give the function's error type and let the conversion resolve:
fn load(path: &Path) -> Result<Config, AppError> {
let text = std::fs::read_to_string(path)?; // io::Error -> AppError
let cfg = serde_json::from_str(&text)?; // serde_json::Error -> AppError
Ok(cfg)
}With Box<dyn std::error::Error> the conversion is still generic; annotating the function's return type is the fix, not annotating each ?.
4. Empty collections and Default
A collection with no elements has nothing to infer from, so the first push or insert must arrive before the ambiguous use — or the type must be written:
let mut names = Vec::new(); // Vec<_>, still open
names.push("a".to_string()); // now Vec<String>
let mut counts = HashMap::new(); // open until insert
counts.insert("a", 0u32);
let empty: Vec<u8> = Vec::new(); // typed from the start
let data = Vec::<u8>::with_capacity(64);Default::default() has the same shape: the type must come from somewhere.
5. Closures and iterator chains
Closures are inferred from their call sites, and a chain that returns an ambiguous type gives an error at the point where the chain is consumed:
let doubled: Vec<i32> = (1..=3).map(|x| x * 2).collect();
// generic helper: the bound is what the compiler needs
fn sum_all<I, T>(items: I) -> T
where
I: IntoIterator<Item = T>,
T: std::iter::Sum,
{
items.into_iter().sum()
}
let total: i64 = sum_all(vec![1i64, 2, 3]);The call site must fix the type for a generic function; the function cannot.
6. Numeric literals and into()
Integer literals default to i32 only when nothing else constrains them, and into() between numeric types has several candidates:
let a = 1; // i32 by default
let b = 1u8.into(); // ambiguous target: E0282 or E0283
let c: u32 = 1u8.into(); // annotated
let d = u32::from(1u8); // or name the conversionPrefer From/from over into when the target type is what you care about; it reads as the destination and removes the inference question. The JSON formatter is useful when the ambiguous value arrived from a config file and you need to see whether it was a number or a string, and the text diff tool shows which annotation was dropped during a refactor.
Common Compilation/Runtime Mistakes & Version Gotchas
- Annotating the wrong side.
collect::<Vec<_>>()still leaves the element type open; put the concrete type in the turbofish or the binding. - Adding
#[allow(...)]or casts to silence it. E0282 is not a lint; a cast somewhere else usually just moves the error. - Relying on a later use. Inference works, but an unused binding is ambiguous; annotate rather than adding a dummy use.
unwrap()instead of the type.parse().unwrap()gives E0282 onparse, not onunwrap; the fix belongs on the earlier call.- Assuming the error names the real problem. The span points at the expression that must be typed, which may be several calls after the design mistake.
- Version notes. Array
into_iter()changed to yield values in Rust 2021, which fixed several ambiguous cases; Rust 2024 keeps that behaviour.impl Traitin argument position andasync fnin traits still require the caller's type to be concrete, so the same annotation rules apply.
Official documentation: E0282 and Iterator::collect.
Official references
primary documentationThe Rust documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust E0463: can't find crate for std
The target triple has no standard library installed. Add the target with rustup, check the target string and link the right ABI.
Rust E0432: unresolved import
E0432 is a module graph problem: a missing mod declaration, a private parent or a wrong path. Fix the tree, not the dependency list.
Rust E0106: missing lifetime specifier
E0106 appears when a returned borrow has no input to borrow from. Name the lifetime in functions, structs and impls, or return owned data.
Rust E0597: borrowed value does not live long enough
E0597 says a borrow outlives the value it points at. Reorder the declarations, own the data, or annotate a lifetime only when the holder truly borrows.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.