Reputation: 191
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);
}
Upvotes: 1
Views: 164
Reputation: 715
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
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);
}
}
}
Upvotes: 1
Reputation: 29981
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.
Upvotes: 1