Skip to main content

EnumerableRef

Trait EnumerableRef 

Source
pub trait EnumerableRef<'a, EnumRef> {
    // Required method
    fn as_enum_ref(&'a self) -> EnumRef;
}
Expand description

A type that can lend itself to the borrowing enum of its sealed trait.

enumerate implements this for every permitted type and makes for<'a> EnumerableRef<'a, AnyShapeRef<'a>> a supertrait. The lifetime is a parameter of the trait rather than of the method, so the higher-ranked bound is nameable in the supertrait list — which is what lets a caller reach the enum from a plain &S:

use closed_trait::{enumerate, sealed};

pub struct Square { pub side: i32 }
pub struct Circle { pub radius: i32 }

#[enumerate(match_any)]
#[sealed(Square, Circle)]
pub trait Shape {}

impl Shape for Square {}
impl Shape for Circle {}

/// Takes a reference, yet still matches exhaustively.
fn corners<S: Shape>(shape: &S) -> u32 {
    match shape.as_enum_ref() {
        AnyShapeRef::Square(_) => 4,
        AnyShapeRef::Circle(_) => 0,
    }
}

fn main() {
    assert_eq!(corners(&Square { side: 1 }), 4);
    assert_eq!(corners(&Circle { radius: 1 }), 0);
}

Enumerable cannot do this: into_enum takes self, so reaching the owned enum means owning the value. The borrowing enum is also the cheaper one to pass, being a pointer and a discriminant rather than as large as the biggest permitted type.

Required Methods§

Source

fn as_enum_ref(&'a self) -> EnumRef

Wraps &self in the variant of EnumRef that holds this type.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§