sealed 0.2.0-rc2

Macro for sealing traits and structures
Documentation

#[sealed]

This crate provides a convenient and simple way to implement the sealed trait pattern, as described in the Rust API Guidelines [1].

[dependencies]
sealed = "0.2.0-rc2"

Example

In the following code structs A and B implement the sealed trait T, the C struct, which is not sealed, will error during compilation.

Examples are available in examples/, you can also see a demo in demo/.

use sealed::sealed;

#[sealed]
trait T {}

pub struct A;

#[sealed]
impl T for A {}

pub struct B;

#[sealed]
impl T for B {}

pub struct C;

impl T for C {} // compile error

fn main() {
    return
}

Details

The #[sealed] attribute can be attached to either a trait or an impl. It supports:

  • Several traits per module
  • Generic parameters
  • Foreign types
  • Blanket impls

Expansion

Input

use sealed::sealed;

#[sealed]
pub trait T {}

pub struct A;
pub struct B(i32);

#[sealed]
impl T for A {}
#[sealed]
impl T for B {}

fn main() {
    return;
}

Expanded

use sealed::sealed;

pub(crate) mod __seal_for_t {
    pub trait Sealed {}
}
pub trait T: __seal_for_t::Sealed {}

pub struct A;
pub struct B(i32);

impl __seal_for_t::Sealed for A {}
impl T for A {}

impl __seal_for_t::Sealed for B {}
impl T for B {}

fn main() {
    return;
}