Why Not
Why Not

Reputation: 51

How to instantiate the same struct with different implementations of a trait?

I have a trait that is implemented by the same struct in different ways. In order to accomplish this I have different structs that have different implementations. For abstraction I'm going to call these structs A-Z:

trait Trait {
    fn bar<T: Trait> (&self, z: &Struct3<T>) -> Struct3<T>;
}
struct StructA {
    name: String,
    color: String,
}
impl Trait for StructA {
    fn bar<T: Trait> (&self, z: &Struct3<T>) -> Struct3<T>{

        let mut list = Vec::new();
        list.push(self.clone());

        let y = Struct2::<T> {
            name: z.y.name,
            list: list,
        };

        Struct3::<T> {
            point: 1,
            y: y,
        }
    }
}
struct StructZ {
    name: String,
    color: String,
}
impl Trait for StructZ {
    fn bar<T: Trait> (&self, z: &Struct3<T>) -> Struct3<T>{

        let mut list = Vec::new();
        list.push(self.clone());

        let y = Struct2::<T> {
            name: z.y.name,
            list: list,
        };

        Struct3::<T> {
            point: 26,
            y: y,
        }
    }
}

Is there another way to approach this so that each instance of the struct has a different implementation of the trait, or is making a new struct the best way to go?

I am new to compiled languages. Most of the work I have done has been using Python and TypeScript.

Upvotes: 4

Views: 2322

Answers (1)

Gymore
Gymore

Reputation: 605

One way to do that is to make your trait generic over some type (even if this type is actually not used inside of the trait).

trait Trait<T> { /* ... */ }

That enables you to implement it multiple times for the same struct.

impl Trait<bool> for Struct { /* ... */ }
impl Trait<u32> for Struct { /* ... */ }

Here, bool and u32 just become compile time flags to chose the implementation of Trait that you want to use.

let struct_3a = Trait::<bool>::bar(&my_object, /* ... */);
let struct_3b = Trait::<u32>::bar(&my_object, /* ... */);

I used bool and u32 here, but you can use your own types here to make everything clearer.

Upvotes: 7

Related Questions