【问题标题】:how to write a function that only takes one variant of the enum as input如何编写一个仅将枚举的一个变体作为输入的函数
【发布时间】:2019-06-02 11:04:37
【问题描述】:

我有一个枚举:

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

有没有办法做到这一点?

【问题讨论】:

    标签: function enums rust


    【解决方案1】:

    enum 的变体是 values 并且都具有相同的 type - enum 本身。函数参数是给定类型的变量,函数体必须对该类型的 any 值有效。所以你想要做的就是行不通。

    但是,设计枚举有一个通用模式,这可能会有所帮助。也就是说,使用单独的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 }) => {}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 2013-12-13
      • 2013-03-19
      • 1970-01-01
      相关资源
      最近更新 更多