I have a generic trait with a "default" implementation that I would like to use with Default::default (playground MWE):
trait Trait<T> {} struct DefaultImpl; impl<T> Trait<T> for DefaultImpl {} I would like to use Box::new(DefaultImpl) as the default value for Box::new(dyn Trait<T>):
impl<T> Default for Box<dyn Trait<T>> { fn default() -> Self { Box::new(DefaultImpl) } } This works OK until T is a reference with a higher-rank trait bound:
// error[E0277]: the trait bound `Box<dyn for<'a> Trait<&'a str>>: Default` is not satisfied // --> src/main.rs:21:46 // | // 21 | let _: Box<dyn for<'a> Trait<&'a str>> = Default::default(); // | ^^^^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `Box<dyn for<'a> Trait<&'a str>>` // | let _: Box<dyn for<'a> Trait<&'a str> I can add another impl Default to cover the case where T is a reference, but I get a conflicting implementations warning:
// warning: conflicting implementations of trait `Default` for type `Box<(dyn Trait<&_> + 'static)>` // --> src/main.rs:13:1 // | // 7 | impl<T> Default for Box<dyn Trait<T>> { // | ------------------------------------- first implementation here // ... // 13 | impl<T: ?Sized> Default for Box<dyn for<'a> Trait<&'a T>> { // | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Box<(dyn Trait<&_> + 'static)>` // | impl<T: ?Sized> Default for Box<dyn for<'a> Trait<&'a T>> { fn default() -> Self { Box::new(DefaultImpl) } } How can I resolve this? I don't fully understand HRTB so I might be taking the wrong approach. I'm not sure how to concisely explain what the real code is doing so that you can give me suggestions for alternate approaches.
1 post - 1 participant
