簡體   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