Incerteza
Incerteza

Reputation: 34884

An instance of different structures as a argument for a function

There're some structures:

struct St1 {
  ..
}

impl St1 {
  pub fn new() -> St1 {
    //.......
  }
}

struct St2 {
  ..
}

impl St2 {
  pub fn new() -> St2 {
    //.......
  }
}

//and so on

There aren't related to each other in terms of inheritance, they don't implement any common interface. I want to create a function which accepts an instance of any of these structs:

fn my_func(???) { .... }

How do I do that? I was thinking about creating a enum:

enum MyEnum {
  St1::new(), //error!
  St2::new()  //error!
}

// and then
fn my_func(en: MyEnum) { .... }

but as you can see it doesn't work. Your ideas?

Note that the structs S1, S2, S3 are from a library so I can't change them.

Upvotes: 1

Views: 125

Answers (1)

ember arlynx
ember arlynx

Reputation: 3281

To create an enum, you'd rather do:

enum MyEnum {
   MySt1(St1),
   MySt2(St2)
}

That is, it has two variants, each carrying data of the respective type.

Another way to do this if you don't care about which variant you have is to define your own trait and implement it for both:

trait Stuff { }
impl Stuff for St1 { }
impl Stuff for St2 { }

fn my_func<T: Stuff>(en: T) { ... }

This has the advantage of not having to duplicate handling and adding an enum. This is called an "extension implementation", since you're extending the type with a trait it didn't used to implement.

Upvotes: 3

Related Questions