static-assertions icon indicating copy to clipboard operation
static-assertions copied to clipboard

Feature request: `assert_type_in`

Open chankyin opened this issue 6 years ago • 1 comments

Assertion that the supplied type must be one of multiple listed types.

One possible (although not so elegant) implementation is like this:

macro_rules! assert_type_in {
    ($label:ident; $type:ty, $($in:ty),*) => {
        mod $label {
            $(fn mux(_: $in) {})*
            fn _(v: $type) {
                mux(v);
            }
        }
    };
}

chankyin avatar Jul 24 '19 06:07 chankyin

I came up with this which seems to work fine (playground):

macro_rules! assert_type_in {
    ($t:ty: $($l:ty),+ $(,)*) => {
        {
            trait InList {}
            $(impl InList for $l {})+

            fn in_list<T: ?Sized + InList>() {}
            let _ = in_list::<$t>;
        }
    }
}

fn main() {
    assert_type_in!(u8: u8, u16);
}

nvzqz avatar Aug 11 '19 20:08 nvzqz