我有一个错误的链接列表,我正在try 遍历这些错误.
type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[derive(Debug)]
struct MyError {
code: Option<u32>,
source: Option<BoxedError>,
}
impl std::error::Error for MyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source().map(|s| s as _)
}
}
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt("", f)
}
}
impl MyError {
fn source(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
self.source.as_ref().map(|c| c.as_ref())
}
fn traverse(&self) -> Option<u32> {
use core::any::Any;
if let Some(code) = self.code {
return Some(code);
}
if let Some(source) = self.source() {
let as_any = &source as &dyn Any;
if let Some(myerr) = as_any.downcast_ref::<MyError>() {
return myerr.traverse();
}
}
None
}
}
这会产生以下错误:
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/lib.rs:31:36
|
26 | fn traverse(&self) -> Option<u32> {
| ----- this data with an anonymous lifetime `'_`...
...
31 | if let Some(source) = self.source() {
| ---- ^^^^^^
| |
| ...is used here...
32 | let as_any = &source as &dyn Any;
| ------- ...and is required to live as long as `'static` here
For more information about this error, try `rustc --explain E0759`.
error: could not compile `playground` due to previous error
考虑到源函数返回一个静态trait对象(这意味着该对象后面没有其他引用,对吗?),我不知道为什么会出现终身错误.