How can I get a Trait from a struct's new method

Suppose I have the following code

pub trait Base {
    fn foo(&self) -> String;
}

struct A {
   name: String,
}

impl  A {
    fn new(x: String) -> Self {
        A {name: x}
    }
}

impl Base for A {
    fn foo(&self) -> String {
        self.name
   }
}

struct B {
    country: String,
}

impl  B {
    fn new(x: String) -> Self {
        B {country: x}
    }
}

impl Base for B {
    fn foo(&self) -> String {
        self.country
   }
}

I want to use the following code, because I want to give a uniform interface.

But I do not know how to convert struct A / B to a Base trait.


def read_data(&self) -> Base {
    let a: Base = A::new("foo".to_string());

    a
}

Depending on what you are doing:

  • it may be best to use a generic bounded by Base,
  • it may be best to use a trait object, or, even
  • it may be best to use an enum containing A and B.

Some more context with what you're doing would be great, especially including how both the A and B types get used/how they overlap.

1 Like

Thanks for your reply, I will try those methods, and the best one.