Pre-RFC: Sealed traits

Another thing we could guarantee about the sealed traits is that dyn Trait: Sized where Trait is a sealed trait and that dyn Trait is laid out exactly the same as an enum with each variant of the enum hold exactly one of the types. This could be huge as it will enable ergonomic error handling. This doesn’t dilute the meaning of dyn, it still means dynamically dispatched, it just changes how it is dispatched. Also with this, sealed traits can be object safe even if they have consuming functions (i.e. functions that take self). no we can’t, generics don’t allow it.

ignore rest of this post

For example (simple example)

trait CustomError {  }

struct DivByZero;
struct SqrtOfNegativeNumber;

impl CustomError for DivByZero {}
impl CustomError for SqrtOfNegativeNumber {}

fn fallible(x: f32) -> Result<f32, dyn CustomError> { // note: dyn CustomError would be Sized
    if x > 0.0 {
        Ok(1.0 / x.sqrt())
    } else if x == 0.0 {
        Err(DivByZero)
    } else {
        Err(SqrtOfNegativeNumber)
    }
}

And this could just work! It is easily extensible and the users of this code can just use the interface provided by the trait (this is a lot like how Pre-RFC: sum-enums works, but more useful).