繁体   English   中英

如何编写仅将枚举的一个变体作为输入的函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM