简体   繁体   English

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

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

相关问题 如何使用带有多个输入的函数的apply()? - How to use apply() with a function that takes more than one input? 如何编写需要一部分函数的函数? - How to write a function that takes a slice of functions? 如何编写一个 function,它将字符串数组作为参数并打印出每个元素的第一个字母(每行一个) - How to write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line) 如何编写带迭代器的 Rust 函数? - How to write a Rust function that takes an iterator? 如何编写仅显示一个类别的函数? - How do I write a function for showing only one category? 如何键入将 arrays 数组作为输入的 function - How to type a function that takes an array of arrays as input 函数如果只接受一个输入 - Function if only accepts one input 如何编写一个名为kellen的MATLAB函数,该函数需要三个名为trs,ch1,ch2的输入参数? - How can I write a MATLAB function named kellen that takes three input arguments named trs, ch1,ch2? 如何在 PHP 中编写 function ,如果输入数组中的任何两个值等于目标总和,则该数组接受一个数组并返回一个数组 - How do I write a function in PHP that takes an array and returns an array if any two values in the input array equal a targeted sum 我如何在 Rstudio 中编写 function 来自动处理数据并将文件名作为输入并返回清理后的数据? - How can i write a function in Rstudio which automates data wrangling and takes as an input the file name and returns the cleaned data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM