In Rust, why does `let n = "42".parse().unwrap();` fail when `n` is only printed afterwards, and how does `parse::<i32>()` fix it?
answer
- generic over the return type
- nothing pins the type parameter
- type annotations needed
- the :: before the angle bracket
basics
~20 sstr::parse is generic over its return type F: FromStr, and printing n does not pin F, so rustc stops with E0284, type annotations needed. The turbofish parse::<i32>() supplies the type argument at the call; let n: i32 works equally well.
solid answer
~40 s`str::parse` is declared `pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>`: the caller chooses `F`, and no argument mentions it. Rust's inference works across the whole function body, so a later `let m: i32 = n;` would settle `F`, but `println!("{}", n)` only needs `Display`, which many types implement. With nothing to go on, rustc reports E0284, "type annotations needed". You fix it by naming the type somewhere inference can see it: on the binding (`let n: i32`), on a later use, or on the call with the turbofish `"42".parse::<i32>()`. The `::` is required in expressions because `parse<i32>()` would read as two comparisons; rustc says "comparison operators cannot be chained" and suggests `::<...>`. The same syntax works on generic functions (`mean::<u16>(&data)`) and type paths (`Vec::<u8>::with_capacity(4)`), and `_` leaves part to inference, as in `collect::<Vec<_>>()`.
code
rust · 4 linesfn main() {
let n = "42".parse().unwrap();
println!("{}", n);
}go deeper
Recall the turbofish syntax ::<> and use it on parse and collect when rustc says type annotations needed.
Explain that functions generic over their return type need evidence from an annotation, a later use or a turbofish, and why expressions need the :: before <.
Place the type where it is decided in a chain, use _ for what inference can supply, and know a turbofish constrains arguments rather than converting them.
Encourage annotations that document intent at decision points in parsing pipelines, so reviewers see each conversion's target type without chasing inference across a function.
## Generic over the return type Most generic functions get their type arguments from their inputs: `max_reading(&[3, 9, 4])` makes `T = i32` because the slice says so. Some std functions are generic over what they **return** instead, so no input carries the type: - `str::parse`, declared `pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>`; - `Iterator::collect`, declared `fn collect<B: FromIterator<Self::Item>>(self) -> B`; - trait methods such as `Default::default()` and `Into::into()`, whose result type the caller chooses. For these, the type must come from somewhere else: a type annotation, a later use, or an explicit **type argument** on the call. ## What rustc says when nothing pins the type Rust's **type inference** is local to a function body but looks at the whole body, not just one line. `let n = "42".parse().unwrap(); let m: i32 = n;` compiles, because the second line fixes `F = i32`. Replace that second line with `println!("{}", n)` and it fails: printing only requires `Display`, and `i32`, `u8`, `f64` and `String` all implement both `Display` and `FromStr`. rustc 1.99.1 reports **E0284**, "type annotations needed", notes that the type must implement `FromStr`, and suggests giving `n` an explicit type. A related message is **E0282**, which appears for `let v = Vec::new();` when nothing later says what the vector holds. Both mean the same thing in practice: a type parameter has no evidence. ## Three ways to supply the type 1. **Annotate the binding**: `let n: i32 = "42".parse().unwrap();`. Inference flows backwards from the annotation through `unwrap` into `parse`. 2. **Use the value in a typed position later**: pass it to a function taking `i32`, or assign it to a typed variable. 3. **Use the turbofish** on the call: `"42".parse::<i32>().unwrap()`. All three produce identical code; the choice is about where a reader expects to see the type. The turbofish wins in method chains, where there is no binding to annotate until the end. ## Why the `::` is required In a type position, `Vec<u8>` is unambiguous. In an **expression**, `parse<i32>()` could be the comparison `parse < i32` followed by `> ()`. The Reference states that the `::` token is required before the opening `<` for generic arguments in expression paths "to avoid ambiguity with the less-than operator", and that this is colloquially known as **turbofish** syntax, from the shape `::<>`. Forget it and rustc says "comparison operators cannot be chained", then suggests the corrected `parse::<i32>()`. The same happens with `Vec<u8>::with_capacity(4)`, which must be `Vec::<u8>::with_capacity(4)`. ## Where a turbofish can go | Form | Example | What it fixes | |---|---|---| | Method | `"42".parse::<i32>()` | the method's own type parameter `F` | | Free generic function | `mean::<u16>(&parsed)` | the function's `T` | | Type path | `Vec::<f32>::with_capacity(4)` | the type's parameter before calling an associated function | | Partial, with `_` | `collect::<Result<Vec<_>, _>>()` | the outer shape, leaving the element and error types to inference | ## A turbofish is a constraint, not a cast Once written, a turbofish fixes the type parameter, and every argument must agree. With `fn mean<T: Copy + Into<f64>>(readings: &[T]) -> f64`: - `mean::<u16>(&[1, 2])` compiles, and the unsuffixed literals become `u16`; - `mean::<u16>(&[1u8, 2])` fails with **E0308**, "expected `u16`, found `u8`", because the turbofish never converts values; - naming a type that misses a bound, such as `mean::<i64>`, fails with E0277 just as an inferred `i64` would. ## When no turbofish is needed Most generic calls never need one, because the evidence is already there: - an argument carries the type, as in `max_reading(&[3, 9, 4])` or `mean(&parsed)`; - the result flows into a typed slot, such as a struct field, a function parameter or an annotated `let`; - the return type of the enclosing function fixes it, as when a function declared `-> Result<u16, ParseIntError>` ends with `s.parse()`. Adding a turbofish in those cases is harmless but redundant, and reviewers usually prefer to leave it out. ## Practical habits - In a parsing pipeline, put the turbofish where the type is decided: `.map(str::parse::<u16>)` reads better than annotating the final vector. - Prefer `collect::<Vec<_>>()` over spelling out the element type the iterator already knows. - When an error says "type annotations needed", ask which generic call has no evidence for its parameter, and add the type there rather than on a distant binding.
- What does `mean::<u16>(&[1u8, 2])` do, given `fn mean<T: Copy + Into<f64>>(readings: &[T]) -> f64`?It fails with E0308, expected `u16`, found `u8`. The turbofish fixes `T = u16`, so the argument must be `&[u16]`; a turbofish never converts values. Dropping the `u8` suffix makes the literals `u16` and the call compiles.
- Why can `let n = "42".parse().unwrap(); let m: i32 = n;` compile without any turbofish?Inference considers the whole function body. The typed assignment on the second line fixes `F = i32` for the earlier `parse` call, so rustc has its evidence. Printing `n` gives no such evidence, because many types implement both `Display` and `FromStr`.
- Can a turbofish leave some type arguments to inference?Yes: write `_` for the parts the compiler can work out. `collect::<Vec<_>>()` fixes the container and lets the element type come from the iterator, and `HashMap::<_, u32>::new()` fixes the value type while a later `insert` decides the key type.
- str::parse returns an i32 unless told otherwise.
- Every call to a generic function needs a turbofish.
- parse<i32>() works without the double colon; the turbofish is just style.
- A turbofish converts the arguments to the named type.
- rustc can infer the parse target from how the value is printed.