Skip to content

std incorrectly states that ? uses Into on the underlying error type #111655

@memoryruins

Description

@memoryruins

Location

/// underlying cause. The '?' operator automatically converts the underlying error type to our
/// custom error type by calling `Into<CliError>::into` which is automatically provided when
/// implementing `From`. The compiler then infers which implementation of `Into` should be used.

Summary

According to the reference and rustc, the ? operator uses the From trait on the underlying error.

For example (playground),

struct A;
struct B;

impl Into<B> for A {
    fn into(self) -> B {
        B
    }
}

fn f(x: Result<(), A>) -> Result<(), B> {
    x?;
    Ok(())
}

rustc 1.71.0-nightly (ce5919fce 2023-05-15)

error[[E0277]](https://doc.rust-lang.org/nightly/error_codes/E0277.html): `?` couldn't convert the error to `B`
  --> src/lib.rs:17:6
   |
16 | fn f(x: Result<(), A>) -> Result<(), B> {
   |                           ------------- expected `B` because of this
17 |     x?;
   |      ^ the trait `From<A>` is not implemented for `B`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `FromResidual<R>`:
             <Result<T, F> as FromResidual<Result<Infallible, E>>>
             <Result<T, F> as FromResidual<Yeet<E>>>
   = note: required for `Result<(), B>` to implement `FromResidual<Result<Infallible, A>>`

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

If the Into<B> impl is replaced with a From<A> impl, the example will successfully compile.

The docs in core/std should no longer state that ? uses Into.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions