Is it possible to have a vec of a struct with generic phantom data in rust?

209 Views Asked by At

I have some struct:

struct Foo<T> {
    // ... non-generic, const fields
    marker: PhantomData<T>    
}

Since PhantomData<T> is of zero-sized, Foo<T> has a compile-time known size. Additionally all Foos are const. Thus, the following should be possible:

I want to create a vector (or array) in which I can store Foo<T>s of different Ts. Perhaps something like Vec<dyn Foo<_>>. This vector I then want to pass to a function:

fn func(foos: &[Foo<_>]) {
    // ...
}

func(&[Foo<i64>::new(), Foo<String>::new()]);

This doesn't work, since (according to the compiler) Foo<A> != Foo<B>, but actually they are the same in terms of memory layout.

Is there a way to do this/some work-around (perhaps using unsafe)?

Using a trait is not what I want since

  • using trait bounds removes the possibility of passing different Ts:

    fn func<T: SomeTrait>(foos: &[T]);
    

    means that I can't pass mixed types, while

  • using dyn SomeTrait requires Boxing which I want to avoid and which should be unnecessary.

I do realize that this is complicated in that some methods of Foo<T> might only be implemented for specific bounds of T, but methods which are implemented for all Ts should still be available.

0

There are 0 best solutions below