I’d like to extract the structs from an enum in Rust:
struct CakeInfo {
best_by: String,
cost_pence: i32,
calories: i32,
}
enum CakeCategory{
Chocolate(CakeInfo),
Sponge(CakeInfo),
Fruit(CakeInfo),
}
If all variants of the enum accept structs of the same type, is there a short hand way to extract this value using the match statement?
What I’d like to do:
cake = CakeCategory::Sponge(CakeInfo {
best_by: "24-10-2024".to_string(),
cost_pence: 450,
calories: 800,
})
cake_best_by = match cake {
_(cake_info) => cake_info.best_by
}
What the compiler instead wants me to do:
cake = CakeCategory::Sponge(CakeInfo {
best_by: "24-10-2024".to_string(),
cost_pence: 450,
calories: 800,
})
cake_best_by = match cake {
Chocolate(cake_info) => cake_info.best_by,
Sponge(cake_info) => cake_info.best_by,
Fruit(CakeInfo) => cake_info.best_by,
}
In the example this isn’t too burdensome but in enums with more variants this becomes very repetitive very quickly. I’m aware of patterns such as if let where the user is only interested in a single enum variant, but that would be more tedious in such a use-case.
Is there any syntax that can do the equivalent to what I’ve attempted?
>Solution :
If all variants have the same payload, this is a very strong indication that your data structure is poorly designed. Consider this design instead:
struct CakeInfo {
best_by: String,
cost: i32,
calories: i32,
category: CakeCategory,
}
enum CakeCategory {
Chocolate,
Sponge,
Fruit,
}
By removing the payloads from all CakeCategory variants, we can simply add a category field to CakeInfo and express exactly the same data but without needing to match to obtain the inner info, especially when we do not care about the category at all.