[英]how to write a function that only takes one variant of the enum as input
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: 我想编写一个仅将
Group::OfTwo
变体作为参数的函数:
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. enum
的变量是值,并且都具有相同的类型 - enum
本身。 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. 也就是说,使用单独的
struct
来保存每个enum
变量的数据。 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: 您以前在
enum
上匹配的任何地方,像这样:
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 }) => {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.