Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readRust
#rust#e0282#type-inference#compiler-errors
Rust inference diagram with an untyped value crate and an annotation plate filling the gap

Introduction & Quick Summary

The code looks complete and rustc stops with a note that points at a variable rather than at a mistake:

code
error[E0282]: type annotations needed --> src/main.rs:4:20 | 4 | let totals = rows.iter().map(|r| r.amount).collect(); | ^^^^^^^ cannot infer type

Quick 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:

rust
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.

rust
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 site

Three 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:

bash
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 build

Inference 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

SiteAmbiguous becauseAnnotation
.collect()many FromIterator implslet v: Vec<T> = … or ::<Vec<T>>()
.parse()any FromStr type::<i32>() or a typed binding
.into() / From::frommany target implstyped binding or ::<Target>()
empty Vec::new(), HashMap::new()no elements to infer fromVec::<u8>::new()
closure returning Default::default()the return type is freeannotate the closure or the binding
? on a generic Resulterror type conversion is openannotate or map_err
ErrorWhat it meansTypical fix
E0282cannot infer at alladd an annotation
E0283multiple candidate implsturbofish on the method
E0284self-referential inferencebreak the generic cycle with a concrete type
E0277trait bound not satisfiedthe type is known, the bound is not met
E0308mismatched typesthe type is known and wrong
Fix styleExampleBest when
binding annotationlet v: Vec<String> = …the variable is used later
turbofishcollect::<Vec<String>>()the value is passed inline
function signaturefn f() -> Result<(), Error>the function owns the type
explicit struct field typestruct 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:

rust
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:

rust
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:

rust
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:

rust
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:

rust
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:

rust
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:

rust
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 conversion

Prefer 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 on parse, not on unwrap; 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 Trait in argument position and async fn in 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 documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.