I have a struct that mostly encapsulates a vector:
struct Group<S> {
elements: Vec<S>
}
I also have a simple trait which is also implemented for other structs:
trait Solid {
fn intersect(&self, ray: f32) -> f32;
}
I want to implement Solid
for Group
, but I want to be able to use Group
both for lists of the same implementation of Solid
and for lists of mixed implementations of Solid
. Basically I want to use both Group<Box<Solid>>
and Group<Sphere>
(Sphere
implements Solid
).
Currently I am using something like this:
impl Solid for Group<Box<Solid>> {
fn intersect(&self, ray: f32) -> f32 {
//do stuff
}
}
impl<S: Solid> Solid for Group<S> {
fn intersect(&self, ray: f32) -> f32 {
//do the same stuff, code copy-pasted from previous impl
}
}
This works, but having line-for-line the same code twice can't be the idiomatic solution. I must be missing something obvious?
In my case I measure a notable performance difference between both trait implementations, so always using Group<Box<Solid>>
isn't a great option.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…