How to get access to enum variant unnamed field?

Viewed 2829

I would like to print data of tuple enum without named fields.

A tuple is a general way of grouping together some number of other values with a variety of types into one compound type.

#[derive(Debug)]
enum Coin {
    Penny(String),
    Nickel { id: String },
}

fn main() {
    let penny = Coin::Penny(String::from("penny"));
    let nickel: Coin = Coin::Nickel { id: String::from("nickel") };

    println!("{} {:?} ", penny.0, penny);
    println!("{:?}", nickel);
}

In this example, Nickel is a struct-like enum variant, whereas Penny is simply called an enum variant.

I get a compiler error:

error[E0609]: no field `0` on type `Coin`
For more information about this error, try `rustc --explain E0609`.
2 Answers

You can use a match statement or alternatively an if let statement to use the variant's associated value:

#[derive(Debug)]
enum Coin {
    Penny(String),
    Nickel { id: String },
}

fn main() {
    let penny = Coin::Penny(String::from("penny"));
    let nickel: Coin = Coin::Nickel {
        id: String::from("nickel"),
    };

    if let Coin::Penny(name) = penny {
        println!("{}", name);
    }

    if let Coin::Nickel{ id } = nickel {
        println!("{}", id);
    }
}

Playground link

Example using match statement:

#[derive(Debug)]
enum Coin {
    Penny(String),
    Nickel { id: String },
}

fn main() {
    let penny = Coin::Penny(String::from("penny"));
    let nickel: Coin = Coin::Nickel {
        id: String::from("nickel"),
    };

    match &penny {
        Coin::Penny(id) => {
            println!("{}; {:?}", id, penny);
        }
        _ => {}
    }

    match &nickel {
        Coin::Nickel { id } => {
            println!("{}; {:?}", id, nickel);
        }
        _ => {}
    }
}

Playground link

Related