Created
July 30, 2018 13:30
-
-
Save yohhoy/5f0096241915d4ce3e4845e9cfdd2981 to your computer and use it in GitHub Desktop.
UnscopedEnum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-------------------------------------------------------- | |
#[derive(Debug, PartialEq, Eq, Copy, Clone)] | |
#[repr(u8)] | |
enum UnscopedEnum { | |
AAA = 1, | |
BBB = 2, | |
CCC = 3, | |
} | |
const AAA: UnscopedEnum = UnscopedEnum::AAA; | |
const BBB: UnscopedEnum = UnscopedEnum::BBB; | |
const CCC: UnscopedEnum = UnscopedEnum::CCC; | |
impl From<u8> for UnscopedEnum { | |
fn from(v: u8) -> UnscopedEnum { | |
// DANGER!! | |
unsafe { std::mem::transmute(v) } | |
} | |
} | |
impl std::fmt::Display for UnscopedEnum { | |
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
match *self { | |
AAA => f.write_str(stringify!(AAA)), | |
BBB => f.write_str(stringify!(BBB)), | |
CCC => f.write_str(stringify!(CCC)), | |
} | |
} | |
} | |
//-------------------------------------------------------- | |
fn main() { | |
let e: UnscopedEnum = 1.into(); | |
println!("e={}", e); | |
if e != BBB { | |
println!("e not equal {}", BBB); | |
} else { | |
println!("e equal {}", BBB); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment