Should a reference to an enum be dereferenced before it is matched?

后端 未结 3 1918
予麋鹿
予麋鹿 2020-12-20 20:58

As a newcomer to Rust, I\'ve stumbled upon two apparently valid ways of running a match on a reference type.

I\'ve defined an enum:

enum         


        
3条回答
  •  春和景丽
    2020-12-20 21:51

    As of Rust 1.26, the idiomatic solution is neither; you don't have to dereference the value or add & to the patterns:

    fn contains_blue(&self) -> bool {
        match self {
            Color::Blue => true,
            Color::Teal => true,
            Color::Purple => true,
            _ => false,
        }
    }
    

    This is thanks to improved match ergonomics.

    You can also use pattern alternation in this case:

    match self {
        Color::Blue | Color::Teal | Color::Purple => true,
        _ => false,
    }
    

提交回复
热议问题