繁体   English   中英

与 Rust 中的枚举匹配的模式

[英]Pattern matching with enum in Rust

我正在做一些 Rust 练习,我很挣扎。 希望我不是唯一一个。

我正在寻找一种仅匹配具有 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);
}

没有这样的模式。

有关模式的更多信息,请参阅本书的模式章节,以及模式参考的语法。 此 position 中没有任何模式允许使用通配符。

在我看来,这个例子中的任务有两个问题,一个是 Chayim Friedman 和 mcarton 暗示的,一个是类型信息显示为字符串。 mcarton 提供的内容非常有帮助。

您的代码稍作修改也可以使用

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);
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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