2

I am using using clonable futures using the shared() method on a future that returns Result<T, Box<dyn Error>>. However, Clone is not implemented for dyn Error. 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. 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. 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)>>
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
H.Z.
  • 81
  • 4
  • 3
    Does this answer your question? [How to clone a struct storing a boxed trait object?](https://stackoverflow.com/questions/30353462/how-to-clone-a-struct-storing-a-boxed-trait-object) – myrtlecat Jan 29 '22 at 01:23

1 Answers1

0

For anyone else wondering, I used Arc instead of Box and it worked perfectly.

H.Z.
  • 81
  • 4