I think I dont understand how to utilize traits properly

51 points BallSpecialist69 68 comments

Hi guys,

I've been learning rust for a few weeks now and I come from a mainly OOP background. I think this is giving me a hard time wrapping my mind around how to properly structure things with the way rust "wants" you to do it. Heres the problem

In my game, I have a GameObject trait

trait GameObject {
    /// Gets the unique ID of this game object used to identify it.
    fn get_id(&self) -> &str;

    /// Gets the action wheel of this object (every object must have one)
    fn get_action_wheel(&self) -> impl ActionWheel;
}

So far so good, the problem is that when I try to make a generic collection of these objects, such as a Vec<dyn GameObject> it doesnt work because the GameObject isnt dyn compatible. I just dont really understand what Im meant to do in scenarios like this. If I wrapped it in an enum, every time I access a wheel from something that implements the GameObject, even if I know the concrete wheel it will return (based on the object), I would still need to check the enum which just seems kind of strange.

Any advice on this? How do you think about this? Appreciate any input.