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