Skip to content

Option as_ref compilation error when implementing cause method for Error trait #53716

Open
@k-viktor

Description

@k-viktor

Hi, I'm new to rust and this looks like a possible bug to me. I implemented my own error type (focus on the cause method implementation in Error trait):

#[derive(Debug)]
pub struct MyError<T: Error>
{
    description: String,
    cause: Option<T>
}

impl <T: Error> fmt::Display for MyError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description)
    }
}

impl <T: Error> MyError<T> {
    pub fn new(description: String, cause: Option<T>) -> MyError<T> {
        MyError{description, cause}
    }
}

impl <T: Error> Error for MyError<T> {
    fn description(&self) -> &str {
        self.description.as_str()
    }

    fn cause(&self) -> Option<&Error> {
        // doesn't work
        //self.cause.as_ref()
        //does work
        match self.cause {
            None => None,
            Some(ref e)=> Some(e)
        }
    }
}

This code seems to work correctly but when I use the commented self.cause.as_ref() instead of the match clause I'm getting following compilation error:

error[E0308]: mismatched types
  --> src\lib.rs:72:9
   |
72 |         self.cause.as_ref()
   |         ^^^^^^^^^^^^^^^^^^^ expected trait std::error::Error, found type parameter
   |
   = note: expected type `std::option::Option<&std::error::Error>`
              found type `std::option::Option<&T>`

I would normally expect it to work because the working match I use as workaround is pretty much the same as the underlying implementation of as_ref() in Option.

Meta

λ rustc --version --verbose
rustc 1.28.0 (9634041 2018-07-30)
binary: rustc
commit-hash: 9634041
commit-date: 2018-07-30
host: x86_64-pc-windows-msvc
release: 1.28.0
LLVM version: 6.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemT-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