FWIW, Kotlin sealed classes are basically this approach to sealed traits, though also being the “data carrying enumerated type” and using the JVMs casting support still.
I wonder if a proc macro could be written to implement this in user code… it would also basically be equivalent to “enum variants are types” while the restriction of implementors being in the same file (macro block) holds.
(I do not have time and should not implement this but)
sketch
#[enum_trait]
pub trait Example {
Case1(String),
Case2 {
alpha: usize,
beta: isize,
}
}
// translates to
mod $unnamable {
pub trait Sealed {}
}
pub trait Example: $unnamable::Sealed {}
pub enum dynExample {
Case1(Case1),
Case2(Case2),
}
pub struct Case1(pub String);
pub struct Case2 {
pub alpha: usize,
pub beta: isize,
}
impl Example for Case1 {}
impl Example for Case2 {}
// plus handle conversions via (Try)Into
// and other derives as well
But having written that, I like the idea of having sealed traits’ vtable instead be an index, so dyn SealedTrait is just the regular struct and the fat pointer has the enum discriminant.
The comparison to “enum variants as types” stands, though.