How to specify Boxed value is particular enum variant?

I want to specify that a struct field will contain a Box<T> where T is a specific enum variant.
Something like:

struct Baz {}

struct Qux {}

enum Bar {
    One(Baz)
    Two(Qux)
}

trait FooBox {
    type Variant;
    fn fooboxable(&self) -> Bar
}

impl FooBox for Baz {
    type Variant = Baz;
    fn fooboxable(&self) -> Bar {
        Bar::One(*self)
    }
}

impl FooBox for Qux {
    type Variant = Qux;
    fn fooboxable(&self) -> Bar {
        Bar::Two(*self)
    }
}

trait TypeEq<A> {}
impl<A> TypeEq<A> for A {}

struct Foo { box: Box<Bar> where Bar::Variant: TypeEq<Baz> }

if this is possible, what is the proper syntax?

You cannot represent enum variants at the type level. One common pattern is to use enums where each variant is a struct:

enum Foo {
    Bar(Bar),
    Baz(Baz),
}

struct Bar { ... }
struct Baz { ... }

EDIT: I see you’ve actually done this at the top of your code. It’s not clear to me what you’re trying to achieve, then.

Your enum will have a different memory layout than the structs in the variants, due to the discriminator, so I don’t think you can convert between them without either cloning or something something hideously unsafe. If you want a guarantee that a field is of that variant, why not just use that inner type?

I think I've got it now, actually.

I've got a struct that I want to accept only one variant of an enum. I think the code in the link accomplishes that albeit with some superfluous code still there from when I was working through things.

Yes, that code works because you’re copying the Foo struct. I think that’s probably the only way to do it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.