Hug*_*aux 11 enums function rust
我有一个枚举:
enum Group {
OfTwo {
first: usize,
second: usize,
},
OfThree {
one: usize,
two: usize,
three: usize,
},
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个仅将Group::OfTwo变体作为参数的函数:
fn proceed_pair(pair: Group::OfTwo) {}
Run Code Online (Sandbox Code Playgroud)
但当我这样做时,我收到消息:
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`
Run Code Online (Sandbox Code Playgroud)
有办法实现这一点吗?
Pet*_*all 17
an 的变体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) {
}
Run Code Online (Sandbox Code Playgroud)
您之前匹配过的任何地方,如下所示enum:
match group {
Group::OfTwo { first, second } => {}
Group::OfThree { first, second, third } => {}
}
Run Code Online (Sandbox Code Playgroud)
您将替换为:
match group {
Group::OfTwo(OfTwo { first, second }) => {}
Group::OfThree(OfThree { first, second, third }) => {}
}
Run Code Online (Sandbox Code Playgroud)