[英]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);
}
在我看来,这个例子中的任务有两个问题,一个是 Chayim Friedman 和 mcarton 暗示的,一个是类型信息显示为字符串。 mcarton 提供的内容非常有帮助。
您的代码稍作修改也可以使用
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.