An enum is a type which can be ONE of a FEW different variants.

rust
// Define an enum.
#[derive(Debug)] // So we can print the contents
enum StuffAndThings {
    // Define the data variants.
    // Variants can be of a number of kinds of data.

    // No data.
    Blah,

    // Single type of data.
    Bleh(u8),

    // Tuple of data.
    Stuff(String, bool),

    // Anonymous struct of data.
    Things{a: String, b: bool},
}

// Create an instance of the enum variants with the double colon.
let blah = StuffAndThings::Blah;
let bleh = StuffAndThings::Bleh(42);
let stuff = StuffAndThings::Stuff(String::from("Stuff"), true);
let things = StuffAndThings::Things{a: String::from("things"), b: true};

// Show the contents.
println!("{:?}", blah); // => Blah
println!("{:?}", bleh); // => Bleh(42)
println!("{:?}", stuff); // => Stuff("Stuff", true)
println!("{:?}", things); // => Things { a: "things", b: true }

Enum Considerations

  • CamelCase is the convention used for Enum definition.

Tags

rust