Rust Enum Usage Examples

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we have a C-like example in Rust that demonstrates how to use enum as C-like enums, including enums with implicit and explicit discriminators.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/type_casting("`Type Conversion and Casting`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/integer_types -.-> lab-99255{{"`Rust Enum Usage Examples`"}} rust/type_casting -.-> lab-99255{{"`Rust Enum Usage Examples`"}} rust/function_syntax -.-> lab-99255{{"`Rust Enum Usage Examples`"}} rust/expressions_statements -.-> lab-99255{{"`Rust Enum Usage Examples`"}} end

C-like

enum can also be used as C-like enums.

// An attribute to hide warnings for unused code.
#![allow(dead_code)]

// enum with implicit discriminator (starts at 0)
enum Number {
    Zero,
    One,
    Two,
}

// enum with explicit discriminator
enum Color {
    Red = 0xff0000,
    Green = 0x00ff00,
    Blue = 0x0000ff,
}

fn main() {
    // `enums` can be cast as integers.
    println!("zero is {}", Number::Zero as i32);
    println!("one is {}", Number::One as i32);

    println!("roses are #{:06x}", Color::Red as i32);
    println!("violets are #{:06x}", Color::Blue as i32);
}

Summary

Congratulations! You have completed the C-Like lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like