Skip to content

Weird compiler error for type annotations #64524

Open
@olegnn

Description

@olegnn
use std::thread;

fn main() {
    let result = {
        let spawned_result = thread::spawn(|| 3).join();
        let result = spawned_result.map_err(|e| e.into());
        let handler = |a| Ok(a + 1);
        result.and_then(handler)
    };

    println!("{:?}", result);
}

(Playground)

Error will be

error[E0282]: type annotations needed for `std::result::Result<i32, E>`
 --> src/main.rs:6:37
  |
4 |     let result = {
  |         ------ consider giving `result` the explicit type `std::result::Result<i32, E>`, where the type parameter `F` is specified
5 |         let spawned_result = thread::spawn(|| 3).join();
6 |         let result = spawned_result.map_err(|e| e.into());
  |                                     ^^^^^^^ cannot infer type for `F`

Which is a little bit confusing because there's no type parameter F in std::result::Result<i32, E>.

On the other hand, if we place let handler = |a| Ok(a + 1); before let result = spawned_result.map_err(|e| e.into());, we will receive correct message:

error[E0282]: type annotations needed for `std::result::Result<i32, E>`
 --> src/main.rs:6:27
  |
4 |     let result = {
  |         ------ consider giving `result` the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified
5 |         let spawned_result = thread::spawn(|| 3).join();
6 |         let handler = |a| Ok(a + 1);
  |                           ^^ cannot infer type for `E`

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions