Best way to return different types from function in trait object

I am trying to write a trait (that must be used as a trait object (in order to be stored in collection)--> therefore no generics), but one of the functions on the trait needs to be able to return different types of data. I could use an enum, but I don't actually know the possible return types (this should be implementable by the library user. I imagine this is a problem that has been encountered by other users, and would like any input on best methods of implementing in a reasonably ergonomic, efficient (and ideally safe) way.

Your description of what you're trying to achieve and why might be a bit too abstract in order to give good suggestions in general. Could you share more details about the concrete use-case, containing e.g.

  • a method signature or perhaps a whole trait defininition of how you're currently implementing your trait (i.e. without worrying about supporting trait objects)
  • enough context so that one can understand how much - or how little - your library can know about those return types

Depending on what you're trying to achieve her, it might make sense e.g. to use a trait object for the return type, too.
It might make sense to use an associated type or generic argument of the trait, as those things are supported for trait objects, just not in a way that gives the same trait-object-type for different associated types or parameters. If that's important, the user would need to ensure to use the same type, e.g. a trait object type or an enum, themself.
Depending on what your library has to do with these trait objects, I could even imagine settings where dyn Any might help.

Concretely, there is a trait:

pub trait Event{
fn exec(&self, mir: &mut Mir)->SomeGenericRetVal

The idea here is that an Event represents some request by the user for the system to do something. the "Mir" argument is a essentially a public interface that allows the user to change the state of the system. All events are contained in an EventQueue, like so:

pub struct EventQueue{
pub events: VecDeque<Box<dyn Event>>

The problem I am having is that whoever implemented the event trait might want to get some data from the system (imagine a "GetName" Event or something). I am unsure how to ergonomically implement such functionality.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.