#traits #sealed #macro #accessible #i32 #self

sealed_trait

A utility for making sealed traits more accessible

2 releases

new 0.1.1 Feb 20, 2025
0.1.0 Feb 20, 2025

#723 in Rust patterns

Custom license

4KB

sealed_trait

A utility for generating sealed traits in Rust. Inspired by Java's sealed class syntax.

Usage

You can create a sealed trait by using the sealed_trait macro:

sealed_trait! {
    pub sealed trait TestTrait permits i32 => {
        fn print_me(self);
    }

    impl TestTrait for i32 => {
        fn print_me(self) {
            println!("{self}")
        }
    }
}

You can also add supertraits to your traits, but they have to be inside square brackets:

sealed_trait! {
    pub sealed trait TestTrait: [Sized, Into<u32>] permits i32 => {
        ...
    }
}

lib.rs:

sealed_trait

A utility for generating sealed traits in Rust. Inspired by Java's sealed class syntax.

Usage

You can create a sealed trait by using the sealed_trait macro:

sealed_trait! {
    pub sealed trait TestTrait permits i32 => {
        fn print_me(self);
    }

    impl TestTrait for i32 {
        fn print_me(self) {
            println!("{self}")
        }
    }
}

You can also add supertraits to your traits, but they have to be inside square brackets and separated by commas, not +:

sealed_trait! {
    pub sealed trait TestTrait: [Sized, Into<i32>] permits i32 => {
        ...
    }
}

Dependencies

~4KB