Return a generic from a function

I want to return a generic instance from a function, how should I do this?

I have the following 2 structs:

struct EX {
    val: u8,

struct EX2 {
    val: u8,

And the following function:

fn parse(input: &str) -> ...
    // HOW?

How cam I make the function parse return either EX or EX2?

One way would be to wrap both in a enum and return it.
Or, if both structs implement the same trait, you can return a Box<dyn CommonTrait>

fn parse(input: &str) -> Box<dyn MyTrait> {

Thx, I'm still new to rust. Does using dyn doesn't have any drawbacks on performance.

Does that matter if it is the way for accomplishing what you want?

By the way, if there's a common trait that both types implement, you can just require the type to be specified:

fn parse<T: MyTrait>(input: &str) -> T {

Incidentally, this is exactly how str::parse() is implemented.

This approach uses static dispatch, while dyn Trait results in dynamic dispatch. This pretty much implies all the advantages and disadvantages of the two different methods.

1 Like

I don't know if it's the only solution.
Here's basically what I try to solve.

I have a string representing a XML and I want to return a struct that represents the input.
Off course, each input might represent a different struct.

Any thoughts?

When you need to dynamically decide the type that comes from deserializing loosely-typed data such as XML, the typical thing to do in Rust is creating an enum as @naim suggested above.

I'd add though that it might be more typical for this use case to define the related types themselves as a single enum.

enum Data {
  EX {
    val: u8,
  EX2 {
    val: u8,

This would be more appropriate if you will not be expecting to write separate functions to deal with the separate data types.

1 Like

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.