This screams for using a struct Season with a name and a weather field. However, I'm using the names in match statements and for this, it appears they need to be constants and not fields of a struct. Is there a way to group constants? Thanks!
I'm not the language designers, but in the general case, patterns work like expressions but backwards, so allowing SPRING.name would be saying that there is a . operator in patterns such that season.name also means something. But it can't bind season because it doesn’t have the weather field, so it would have to be restricted only to comparing to constants, which is weird. And, we have the const {} syntax with a clearly defined meaning applicable here, which just doesn’t have all the details considered yet.
Also, it’s just not especially common; this thread is the first time I’ve ever seen someone wanting to match against a constant’s struct field. Matches of this character would usually involve an enum instead of a string comparison, and you can use a macro library like strum to do the matching that creates the enum in the first place. If you didn’t want to use the macro, it’s still only a few lines to declare the string-to-enum conversion manually.
use std::str::FromStr;
#[derive(Clone, Copy, Debug, strum::EnumString, strum::Display)]
#[strum(serialize_all = "kebab-case")]
enum Season {
Spring,
Summer,
Fall,
Winter,
}
impl Season {
fn weather(self) -> &'static str {
match self {
Season::Spring => "warm",
Season::Summer => "hot",
Season::Fall => "rainy",
Season::Winter => "cold",
}
}
}
fn main() {
let season = Season::from_str("spring").unwrap();
println!("{season} is {}", season.weather());
}
The :: operator can (and should) be used in match patterns - and in my mind, . is almost the same. Indeed, . is used instead of :: in various languages, including Scala (and Python?) where it can be used in matches.
I'm mostly concerned about matches of input such as this one.