How to have a list of a type which needs generic traits in one of its properties?
⚓ Rust 📅 2026-04-15 👤 surdeus 👁️ 5Here is a brief overview of what I want to achieve:
I have a struct called Constraint defined the following way:
pub struct Constraint<JointType: Joint> {
...
joint: JointType,
...
}
and I have many struct defined which implements the Joint trait.
pub struct RevoluteJoint {}
pub struct SphericalJoint {}
....
But I want to store a list of Constraint instances.
I tried Vec<Constraint<JointType>> but that won't work because the compiler wants a list of only a specific joint type. I want a list which can hold the Constraint made with any type of JointType. How can I create a list of Constraint which can hold any JointType?
It seems to me that the easiest way is to just remove the Constraint struct and put everything in Constraint struct into all the Joint trait implementation and create a list with the following:
Vec<Box<dyn Joint>>
The above is possible but the reason I created Constraint because there are a lot of data which is same for each JointType and implementing them in each struct will make the code very verbose and error prone if I want to create a new JointType later on and forget a specifc data piece...
9 posts - 4 participants
🏷️ Rust_feed