FAQ - Help and questions

How do I fix "type annotations needed" with parse and collect (E0282, E0284)?

#errors#types#inferencepublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

Methods like parse and collect can produce many types, and nothing in the code says which one you want. Name the type where you declare the variable, as in let numbers: Vec<i32> = ..., or on the call with a turbofish such as parse::<i32>() or collect::<Vec<i32>>().

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Rust infers most types, but it will not guess when several are possible. parse() can return any type that implements FromStr, and collect() can build a Vec, a HashSet, a String and many others. If nothing later in the function pins the type down, the compiler stops and asks. Depending on the code, the error code is E0282 or E0284; the fix is the same.

src/main.rsrust
fn main() {
    let numbers = "1 2 3".split(' ').map(|s| s.parse().unwrap()).collect();
    println!("{:?}", numbers);
}
text
error[E0284]: type annotations needed
 --> src/main.rs:2:48
  |
2 |     let numbers = "1 2 3".split(' ').map(|s| s.parse().unwrap()).collect();
  |                                                ^^^^^ cannot infer type of the type parameter `F` declared on the method `parse`
  |
  = note: cannot satisfy `<_ as FromStr>::Err == _`
help: consider specifying the generic argument
  |
2 |     let numbers = "1 2 3".split(' ').map(|s| s.parse::<F>().unwrap()).collect();
  |                                                     +++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0284`.

The answers below are the two ways to say the type.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: annotate the variable#

    Put the type after the variable name. This is the shortest, and the type also documents what the variable holds.

    src/main.rsrust
    fn main() {
        let numbers: Vec<i32> = "1 2 3".split(' ').map(|s| s.parse().unwrap()).collect();
        println!("{:?}", numbers);
    }
    text
    [1, 2, 3]
      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: use the turbofish#

      Write the type on the method, ::<Type>. Use it when there is no variable to annotate, for example inside a longer expression:

      rust
      fn main() {
          let total: i32 = "1 2 3".split(' ').map(|s| s.parse::<i32>().unwrap()).sum();
          println!("{total}");
      }

      The _ placeholder lets the compiler fill in what it can: collect::<Vec<_>>() names the container and leaves the item type to inference.

      Common mistakes#

      • Annotating the wrong place. The message points at the method call; the type you add must be the type that call returns.
      • Calling .sum() or .product() without a type: they need a target type as well.
        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail