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

This example demonstrates how to use enum with methods in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Basics Examples