Skip to content

The Try trait causes str::parse to infer the unit type () #94902

Open
@spikespaz

Description

@spikespaz

Given the following code:

Playground

fn main() {
    || -> anyhow::Result<_> {
        Ok("5".parse::<_>()? / 5.0_f64)
    }().unwrap();
}

The current output is:

Compiling playground v0.0.1 (/playground)
error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): cannot divide `()` by `f64`
 [--> src/main.rs:3:30
](https://play.rust-lang.org/#)  |
3 |         Ok("5".parse::<_>()? / 5.0_f64)
  |                              ^ no implementation for `() / f64`
  |
  = help: the trait `Div<f64>` is not implemented for `()`

error[[E0277]](https://doc.rust-lang.org/stable/error-index.html#E0277): the trait bound `(): FromStr` is not satisfied
    [--> src/main.rs:3:16
](https://play.rust-lang.org/#)     |
3    |         Ok("5".parse::<_>()? / 5.0_f64)
     |                ^^^^^ the trait `FromStr` is not implemented for `()`
     |
note: required by a bound in `core::str::<impl str>::parse`

error[[E0283]](https://doc.rust-lang.org/stable/error-index.html#E0283): type annotations needed
 [--> src/main.rs:3:28
](https://play.rust-lang.org/#)  |
3 |         Ok("5".parse::<_>()? / 5.0_f64)
  |                            ^ cannot infer type for type parameter `E`
  |
  = note: multiple `impl`s satisfying `anyhow::Error: From<_>` found in the following crates: `anyhow`, `core`:
          - impl<E> From<E> for anyhow::Error
            where E: 'static, E: std::error::Error, E: Send, E: Sync;
          - impl<T> From<T> for T;
  = note: required because of the requirements on the impl of `FromResidual<Result<Infallible, _>>` for `Result<_, anyhow::Error>`

Some errors have detailed explanations: E0277, E0283.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `playground` due to 3 previous errors

Ideally the output should look like:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.16s
     Running `target/debug/playground`

If a type is provided to str::parse via the turbofish, rather than leaving it anonymous as _, the code compiles well.

fn main() {
    || -> anyhow::Result<_> {
        Ok("5".parse::<f64>()? / 5.0_f64)
    }().unwrap();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-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