[英]how to write a function that only takes one variant of the enum as input
我有一个枚举:
enum Group {
OfTwo { first: usize, second: usize },
OfThree { one: usize, two: usize, three: usize },
}
我想编写一个仅将Group::OfTwo
变体作为参数的函数:
fn proceed_pair(pair: Group::OfTwo) {
}
但是当我这样做时,我得到消息:
error[E0573]: expected type, found variant
有没有办法做到这一点?
enum
的变量是值,并且都具有相同的类型 - enum
本身。 函数参数是给定类型的变量,并且函数主体必须对该类型的任何值有效。 因此,您要做的只是行不通。
但是,存在设计枚举的通用模式,这可能会有所帮助。 也就是说,使用单独的struct
来保存每个enum
变量的数据。 例如:
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) {
}
您以前在enum
上匹配的任何地方,像这样:
match group {
Group::OfTwo { first, second } => {}
Group::OfThree { first, second, third } => {}
}
您将替换为:
match group {
Group::OfTwo(OfTwo { first, second }) => {}
Group::OfThree(OfThree { first, second, third }) => {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.