kvarn::prelude::utils::prelude::compact_str::core::mem

Function discriminant

1.21.0 (const: 1.75.0) · source
pub const fn discriminant<T>(v: &T) -> Discriminant<T>
Expand description

Returns a value uniquely identifying the enum variant in v.

If T is not an enum, calling this function will not result in undefined behavior, but the return value is unspecified.

§Stability

The discriminant of an enum variant may change if the enum definition changes. A discriminant of some variant will not change between compilations with the same compiler. See the Reference for more information.

The value of a Discriminant<T> is independent of any free lifetimes in T. As such, reading or writing a Discriminant<Foo<'a>> as a Discriminant<Foo<'b>> (whether via transmute or otherwise) is always sound. Note that this is not true for other kinds of generic parameters and for higher-ranked lifetimes; Discriminant<Foo<A>> and Discriminant<Foo<B>> as well as Discriminant<Bar<dyn for<'a> Trait<'a>>> and Discriminant<Bar<dyn Trait<'static>>> may be incompatible.

§Examples

This can be used to compare enums that carry data, while disregarding the actual data:

use std::mem;

enum Foo { A(&'static str), B(i32), C(i32) }

assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz")));
assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2)));
assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3)));

§Accessing the numeric value of the discriminant

Note that it is undefined behavior to transmute from Discriminant to a primitive!

If an enum has only unit variants, then the numeric value of the discriminant can be accessed with an as cast:

enum Enum {
    Foo,
    Bar,
    Baz,
}

assert_eq!(0, Enum::Foo as isize);
assert_eq!(1, Enum::Bar as isize);
assert_e