简体   繁体   中英

Pattern matching with enum in Rust

I'm doing some Rust exercises and I'm struggling a lot. Hope I'm not the only one.

I'm searching for a way to match the pattern for only the coins that have a state.

Coin::*(state) => result.push_str(format!("{:?} from {:?}", coin, state).as_str()),

#[derive(Debug)]
#[allow(dead_code)]
pub enum State {
    Alabama,
    Alaska
}

#[derive(Debug)]
#[allow(dead_code)]
pub enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(State)
}

fn main() {
    let coin = Coin::Quarter(State::Alabama);
    let penny = Coin::Penny;
    get_coin_information(&penny);
    get_coin_information(&coin);
}

pub fn get_coin_information(coin: &Coin)
{
    let mut result = String::from("The coin is a ");

    match coin {
        Coin::*(state) => result.push_str(format!("{:?} from {:?}", coin, state).as_str()),
        other => result.push_str(format!("{:?}", other).as_str())
    }

    let result = result + ".";

    println!("{}", result);
}

There is no such pattern.

See pattern chapter of the book for more information about patterns, and the patterns reference for their grammar. No pattern allows a wildcard in this position.

In my opinion, there are two issues in this task arising from the example, one that Chayim Friedman and mcarton hinted at and the display of type information as string. What mcarton has provided is very helpful.

Your code with a little modification will also work

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=af81626a5caeaedf49866ed2346e3948

use std::fmt::{self, Debug, Display};

#[derive(Debug)]
pub enum State {
    Alabama,
    Alaska
}

#[derive(Debug)]
pub enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(State)
}

impl Display for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Display for Coin {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

fn main() {
    let coin = Coin::Quarter(State::Alabama);
    let penny = Coin::Penny;
    get_coin_information(&penny);
    get_coin_information(&coin);
}

pub fn get_coin_information(coin: &Coin)
{
    

    match coin {
        //It is written so that it is easy to debug.
       Coin::Penny | Coin::Nickel | Coin::Dime  => {
            let msg = format!("The coin status {}", coin);
            println!("{}", msg);
        },
        _ => {
            println!("The coin status other {:?}", coin);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM