Summary
The idea is to add struct groups. Similar to enums in structure. You have a group name and then variants under it. Each “variant” would be a reference to a struct that has been defined. You could then use this group as a type for arguments in functions and as a return type. But you could also address individual structs normally. When the group name is used for a type, it acts like an enum and you would need match to get which variant it is.
Motivation
This is useful in cases where you want to accept any struct from a range of structs, but then you also want to be able to return individual variants of the group from some functions without having to return the entire enum and leave the end use having to do a match case just to get the result.
Detailed design
The structure would very much be like an enum. So I’ll start with the syntax.
struct Item1 {
...
}
struct Item2 {
...
}
group Items {
Item1,
Item2,
}
fn purchase(item: Items) {
match search_items("foo") {
Item1 => { ... },
Item2 => { ... },
}
// To show you can accept it as an argument
}
fn search_items(s: &str) -> Option<Items> {
// Showing that you would be able to return `Items`
// The code running this would be similar to when you return an enum
// match search_items("foo") {
// Item1 => { ... },
// Item2 => { ... },
// }
}
fn item2_to_item1(item: Item2) -> Item1 {
// This is to show that you can still use the structs as normal
}
As shown in the examples, it would work just as an enum except that the pieces are previously made structs which you can still use on their own. Not much I think I could explain really. Sorry if I’m not providing enough detail.
How We Teach This
This is a fairly simple concept and can be taught right along with enums since it relates mostly to it. A small section about groups and their uses would be needed. For terminology I’m not sure what to call the structs in the group. Something like members or items. Variants doesn’t seem appropriate.
Drawbacks
It seems slightly redundant as its super close to Enums
Alternatives
Using an enum with unit variants for everything that just point to a struct. (Which is not that elegant) You could also use traits but you cant have your return type as “a struct that implements X” iirc.
Unresolved questions
Besides what to call the structs in the group, not any that I have, but I’m sure I might have missed something, which is why I’m coming here for feedback.