Issues with Boxed trait objects

⚓ Rust    📅 2026-04-16    👤 surdeus    👁️ 3      

surdeus

I am having some issues with trait objects and Box, and don't understand how it all works well enough to troubleshoot.

I have the following code (simplified), and whenever I call methods on an element of the Vec, I get method not found, or trait bound issues.


use egui::widget::Widget

// Just intended to be a marker trait.
trait SchematicConnector: Widget {}

struct RightAngle {
//implementation omitted.
}

impl Widget for &mut RightAngle {
//implementation omitted.
}

impl SchematicConnector for RightAngle {}

struct MultiRightAngle {
    inner_connectors: Vec<Box<dyn SchematicConnector>>,
//implementation omitted.
}

impl Widget for &mut MultiRightAngle {
//implementation omitted.
}

impl SchematicConnector for MultiRightAngle {}


let connections: Vec<Box<dyn SchematicConnector>> = Vec::new();

connections.push(Box::new(RightAngle{}));
connections.push(Box::new(MultiRightAngle{
// populate inner vec
}));

for connection in connections {
    // do something if connection type = RightAngle
    // do something if connection type = MultiRightAngle

    // call method from Widget impl on either type
}

I tried to do this with Any and kept running into issues with unimplemented traits and poor error messages.

I also attempted to create an enum and match on that, however that resulted in duplicating the code that is common for both RightAngle and MultiRightAngle

enum ConnectorType {
    RightAngle(RightAngle),
    MultiRightAngle(MultiRightAngle),
}

If I attempt to call ui.place(connection) for example, I have to unwrap the enum to get the inner value, and then do that as many times as I have enum variants, even though they all impl Widget.

The enum solution "works", but is very fiddly. I could not get the Any solution to work at all, even though it seems like it is the more "rusty?" somehow.

Any advice or suggestions would be appreciated!

3 posts - 3 participants

Read full topic

🏷️ Rust_feed