'How to write a function that only accepts one enum variant as input?
I have an enum:
enum Group {
OfTwo {
first: usize,
second: usize,
},
OfThree {
one: usize,
two: usize,
three: usize,
},
}
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 `Group::OfTwo`
--> src/lib.rs:13:23
|
13 | fn proceed_pair(pair: Group::OfTwo) {}
| ^^^^^^^^^^^^
| |
| not a type
| help: try using the variant's enum: `crate::Group`
Is there a way to achieve this?
Solution 1:[1]
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 }) => {}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |