RRust By Example
intermediateBasics

Enum with Methods

Implement methods on enums.

Enum with Methods

Implement methods on enums.

Difficulty

Intermediate

Code

rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

impl Coin {
    fn value_in_cents(&self) -> u32 {
        match self {
            Coin::Penny => 1,
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter => 25,
        }
    }

    fn name(&self) -> &str {
        match self {
            Coin::Penny => "penny",
            Coin::Nickel => "nickel",
            Coin::Dime => "dime",
            Coin::Quarter => "quarter",
        }
    }
}

fn main() {
    let coins = vec![Coin::Penny, Coin::Quarter, Coin::Dime];
    for coin in &coins {
        println!("{}: {} cents", coin.name(), coin.value_in_cents());
    }
}

Explanation

Enums can have methods via impl.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples