I have an enum:
enum Group {
OfTwo { first: usize, second: usize },
OfThree { one: usize, two: usize, three: usize },
}
and I would like to write a function that only takes as argument the Group::OfTwo
variant:
fn proceed_pair(pair: Group::OfTwo) {
}
But when I do that, I get the message:
error[E0573]: expected type, found variant
Is there a way to achieve this?
The variants of an enum
are values and all have the same type - the enum
itself. A function argument is a variable of a given type, and the function body must be valid for any value of that type. So what you want to do will just not work.
However, there is a common pattern for designing enums, which might help here. That is, to use a separate struct
to hold the data for each enum
variant. For example:
enum Group {
OfTwo(OfTwo),
OfThree(OfThree),
}
struct OfTwo { first: usize, second: usize }
struct OfThree { one: usize, two: usize, three: usize }
fn proceed_pair(pair: OfTwo) {
}
Anywhere that you previously matched on the enum
like this:
match group {
Group::OfTwo { first, second } => {}
Group::OfThree { first, second, third } => {}
}
You would replace with:
match group {
Group::OfTwo(OfTwo { first, second }) => {}
Group::OfThree(OfThree { first, second, third }) => {}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.