How to create an enumeration of constants with and without explicit values in Rust

1 Answer

0 votes
/* 
   Title: Enumeration of Constants in Rust
   Example with and without explicit values
*/

#[derive(Debug)]
// Enum WITHOUT explicit values
// Rust automatically assigns no numeric values unless you use repr()
enum Color {
    Red,      // index-like position 0
    Green,    // 1
    Blue,     // 2
}

#[derive(Debug)]
// Enum WITH explicit values using repr() and manual assignment
#[repr(i32)]
enum Status {
    OK = 1,
    Warning = 5,
    Error = 6,
    Critical = 10,
}

fn main() {
    println!("Enum without explicit values:");
    println!("Red = {:?}", Color::Red);
    println!("Green = {:?}", Color::Green);
    println!("Blue = {:?}", Color::Blue);

    println!("\nEnum with explicit values:");
    println!("OK = {}", Status::OK as i32);
    println!("Warning = {}", Status::Warning as i32);
    println!("Error = {}", Status::Error as i32);
    println!("Critical = {}", Status::Critical as i32);
}



/* 
run:

Enum without explicit values:
Red = Red
Green = Green
Blue = Blue

Enum with explicit values:
OK = 1
Warning = 5
Error = 6
Critical = 10

*/

 



answered Apr 26 by avibootz

Related questions

...