I am trying to implement std::error::Error trait, based on Error Handling section of Rust Book
https://doc.rust-lang.org/book/error-handling.html
But I can't get the following code compiled:
playground url: Rust Playground
use std::error;
use std::fmt;
use std::any::Any;
#[derive(Debug)]
pub struct Err<T>(T);
impl<T:fmt::Debug+Any> error::Error for Err<T> {
fn description(&self) -> &str { "_" }
}
impl<T: fmt::Debug> fmt::Display for Err<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_") }
}
#[derive(Debug)]
pub struct Foo<'a> (Err<&'a str>);
impl<'a> fmt::Display for Foo<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "_") }
}
impl<'a> error::Error for Foo<'a> {
fn description(&self) -> &str { "_" }
fn cause(&self) -> Option<&error::Error> {
// None // OK
// Some(self) // OK
Some(&self.0) // error[E0477]: the type `&'a str` does not fulfill the required lifetime
// note: type must outlive the static lifetime
}
}
Why I can wrap self without lifetime problem but can't wrap &self.0 ??? why static lifetime???
How can I annotate lifetime to make it work?
Thanks!