Skip to content

question mark and try! obscure type inference errors #38508

Open
@tinaun

Description

@tinaun
use std::num::ParseIntError;

fn run() -> Result<(), ParseIntError> {
    let v = vec![1,2,3];

    let x = "1".parse()?;
    
    println!("{:?}", v[x]);    
    Ok(())
}

fn main() {
    let _ = run();
}

has the confusing error message

error[E0277]: the trait bound `(): std::str::FromStr` is not satisfied
 --> <anon>:6:17
  |
6 |     let x = "1".parse()?;
  |                 ^^^^^ the trait `std::str::FromStr` is not implemented for `()`

error[E0277]: the trait bound `std::vec::Vec<i32>: std::ops::Index<()>` is not satisfied
 --> <anon>:8:22
  |
8 |     println!("{:?}", v[x]);
  |                      ^^^^ the trait `std::ops::Index<()>` is not implemented for `std::vec::Vec<i32>`
  |
  = note: the type `std::vec::Vec<i32>` cannot be indexed by `()`

replacing the ? with .unwrap() gives a nicer explanation of the problem (try! gives the same error message as ?)

error[E0282]: unable to infer enough type information about `_`
 --> <anon>:6:9
  |
6 |     let x = "1".parse().unwrap();
  |         ^ cannot infer type for `_`
  |
  = note: type annotations or generic parameter binding required

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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