Access the parameters of the Enum's fields

Let's say I have an enum

#[derive(Debug)]
enum Adder {
  Add(u32, u32),
  Printer(String),
}

impl Adder {
  fn add_now(&self) -> u32 {
    // I want to access the 2 parameters that I pass as Adder::Add(1, 2) in the main function
  }
}

fn main() {
  let a = Adder::Add(1, 2);
  println!("{:?}", a.add_now());
}

Look at the comment in the add_now method. How do I access the 2 arguments that I passed to Adder::Add in the main function?

You basically have to match your instance (&self) against a pattern to get access to the fields. Note that your add_now has to handle all variants of your Adder enum. After all, I can call Adder::Printer("string".to_owned()).add_now(). What should add_now do in that case? You have to think about that when designing your API. Here is an example where I left your return type intact and return 0 for the Printer variant:

#[derive(Debug)]
enum Adder {
    Add(u32, u32),
    Printer(String),
}

impl Adder {
    fn add_now(&self) -> u32 {
        match self {
            Self::Add(a, b) => a + b,
            Self::Printer(_) => 0,
        }
    }
}

fn main() {
    let a = Adder::Add(1, 2);
    println!("{:?}", a.add_now());
}

Playground.

Chapter 6 of the book discusses enums and pattern matching in more detail.

3 Likes