What is the syntax to match on a reference to an enum?

Edit: Please see Shepmaster's answer for the latest idiom

The idiomatic way would be

match *self {
    Animal::Cat(ref c) => f.write_str("c"),
    Animal::Dog => f.write_str("d"),
}

You can use _ instead of ref c to silence the "unused" warning.


As of Rust 1.26, the idiomatic way is the way that you originally wrote it because match ergonomics have been improved:

use std::fmt;

pub enum Animal {
    Cat(String),
    Dog,
}

impl fmt::Display for Animal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Animal::Cat(_) => f.write_str("c"),
            Animal::Dog => f.write_str("d"),
        }
    }
}

fn main() {
    let p: Animal = Animal::Cat("whiskers".to_owned());
    println!("{}", p);
}

Tags:

Rust