How to use trait implemented by unit-like structs, to "subtype" a struct


#1

Hello,

I’m using a Unit-like struct implementing a certaint trait as a generic type
for another struct.

Boiling it down, I have something like this:

pub trait MyTrait {
    fn value(&self) -> u8;
}

pub struct MySimpleStruct;

impl MyTrait for MySimpleStruct {
    fn value(&self) -> u8 { 1 }
}

pub struct MyComplicatedStruct<MyTrait> {
    saved_value: u8,
    argument: MyTrait
}

impl<T> MyComplicatedStruct<T> {
    pub fn new(argument: T) -> MyComplicatedStruct<T>
    where
        T: MyTrait
    {
        let saved_value = argument.value();

        MyComplicatedStruct {
            saved_value,
            argument
        }
    }
}

My question is, is there some way of associating MyComplicatedStruct with one
implementation of MyTrait, without actually storing it as a value in each
instance of MyComplicatedStruct?

I tried just removing the line argument: MyTrait, but that results in the
error unused type parameter.

Am I on the right track but just missing some detail? Is there some completely different but more Rustic way of achieving the same thing? Please help.

Thanks,
Björn


#2

Store PhantomData<MyTrait> inside MyComplicatedStruct.

https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html


#3

That will do it. Thanks!


#4

Used this approach in my first little crate:

https://crates.io/crates/video-timecode