Note: My question is similar to this question, but doesn't seem to solve my use case. Can enum variants have constant associated values?
Problem explanation
My server returns a country (very long list) which internally is mapped to an enum (there is a closed set of valid possibilities known ahead of time).
I need to have some data associated to the country (for instance the language).
The associated data is "constant" and for ergonomic/performance reasons it makes sense for the data to be "attached" to the enum variation.
Contrived example:
I have a list of languages and a list of countries
#[derive(Serialize,Deserialize)
enum Language {
English,
Spanish,
French,
// .. 100 more
}
#[derive(Serialize,Deserialize)
enum Country {
USA,
England,
France,
Mexico,
Spain
// .. 100 more
}
Internally I would like the enum to associate the language value to the country implicitly:
// what I want
#[derive(Serialize,Deserialize)
enum Country {
USA(Language),
England(Language),
// ... more countries with associated languages...
}
- When creating a "Country", I don't want to supply the language, rather just
Country::country_name
(without the language) - when serializing/deserializing, the language should be implicitly added
Looking at serde.rs documentation you could add a field attribute
#[serde(default)]
or
#[serde(default = "path")]
but
default
there isn't a default language for all countries - rather it depends on the country variant it is contained inpath
- the function is called without the country value, so similar effect todefault
Some options I considered
- implement serialize/deserialize by hand - but i have many cases and error prone
- lazy constant values ? verbose
Not an ideal solution but reasonable in my use case:
use
lazy_static
orconst
data (in my situation the data wasn't const'able per the example in the question)