Phantom generics on enums

Hi there!

I'm currently working on a virtual DOM library, where elements' event handlers are messages of a given type. The DOM is built around nodes, which are either plain strings or elements.

One point of the library is that we can use elements from other libraries, such as typed_html, as virtual elements are represented using a trait:

trait VElement<M> { // 'M' is the type of event handlers
  // ...
}

// Support for `typed_html`
impl<M> VElement<M> for DOMTree<M> {
  // ...
}

Now I struggle at creating the VNode enum which can be either a simple string or a virtual element. I've tried this:

enum VNode<T: VElement<M>, M> {
  Text(String),
  Element(T)
}

But this doesn't work as the compiler keeps telling me M is never used in the enum. So, how can I do? I can't find a way to solve this :confused:

Thanks for your help ! :slight_smile:

EDIT : I already thought about creating a wrapper structure with a std::marker::PhantomData inside, but I don't want to have to deal with a wrapper just for this.

So, I finally found a solution :sweat_smile:
Unlike what I thought, if I put the M parameter of VElement as an associated type instead of a type parameter, VNode can be written this way:

enum VNode<T: VElement> {
  // ...
}

And specifying the associated type of VElement is not mandatory here. So my problem is solved!

I let this post here so anyone with the same problem can see the solution :slight_smile:

1 Like