[英]How to clone a boxed trait Error ( Box<dyn Error> )?
I'm new to rust, I am using using clonable futures using the shared() method on a future that returns Result<T, Box<dyn Error>>
.我是 rust 的新手,我在返回
Result<T, Box<dyn Error>>
的未来上使用 shared() 方法使用可克隆期货。 However, Clone is not implemented for dyn Error.但是,克隆并未针对 dyn 错误实现。 I tried creating my own custom error type (
CustomError
) that wraps Box<dyn Error>
instead and tried to implement Clone on that but it still doesn't work.我尝试创建自己的自定义错误类型(
CustomError
)来包装Box<dyn Error>
并尝试在其上实现 Clone 但它仍然不起作用。 I feel like I am missing something trivial here.我觉得我在这里遗漏了一些微不足道的东西。
Here's what I tried这是我尝试过的
use std::error::Error;
#[derive(Debug)]
pub struct CustomError(pub Box<dyn Error>);
impl Clone for CustomError{
fn clone(&self) -> Self {
CustomError(Box::*new*(self.0.clone())) // doesn't work due to unsatisfied trait bounds, what else can I do?
}
}
Here's the error I get if I try to use Box<dyn Error>
as my return type when calling shared() on the future.这是我在将来调用 shared() 时尝试使用
Box<dyn Error>
作为返回类型时得到的错误。 Any solutions to this?有什么解决办法吗?
error[E0277]: the trait bound `(dyn StdError + 'static): Clone` is not satisfied
--> src/scrapers/form_4_xml_scraper.rs:56:52
|
56 | let document_fut = self.scrape(filing).shared();
| ^^^^^^ the trait `Clone` is not implemented for `(dyn StdError + 'static)`
|
= note: required because of the requirements on the impl of `Clone` for `Box<(dyn StdError + 'static)>`
= note: 1 redundant requirements hidden
= note: required because of the requirements on the impl of `Clone` for `std::result::Result<(Filing, Form4XMLDocument), Box<(dyn StdError + 'static)>>
For anyone else wondering, I used Arc
instead of Box
and it worked perfectly.对于其他想知道的人,我使用
Arc
而不是Box
,并且效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.