It seems like every introductory document for Rust's enum types explains how to match on an enum object that you own, but what if you do not own the enum object and you just have a reference to it that you want to match against? I don't know what the syntax would be.
Here is some code where I attempt to match on a reference to an enum:
use std::fmt; use std::io::prelude::*; pub enum Animal { Cat(String), Dog, } impl fmt::Display for Animal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Animal::Cat(c) => f.write_str("c"), Animal::Dog => f.write_str("d"), } } } fn main() { let p: Animal = Animal::Cat("whiskers".to_owned()); println!("{}", p); }
The Rust Playground gives errors on the first two cases of the match when trying to compile it:
error[E0308]: mismatched types --> src/main.rs:12:13 | 12 | Animal::Cat(c) => f.write_str("c"), | ^^^^^^^^^^^^^^ expected &Animal, found enum `Animal` | = note: expected type `&Animal` = note: found type `Animal` error[E0308]: mismatched types --> src/main.rs:13:13 | 13 | Animal::Dog => f.write_str("d"), | ^^^^^^^^^^^ expected &Animal, found enum `Animal` | = note: expected type `&Animal` = note: found type `Animal`
How can I change that code to get it to compile? I tried adding ampersands in lots of different places without any luck. Is it even possible to match on a reference to an enum?
Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... };
Bookmark this question. Show activity on this post. struct Point { x: f64, y: f64, } enum Shape { Circle(Point, f64), Rectangle(Point, Point), } let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }
ref annotates pattern bindings to make them borrow rather than move. It is not a part of the pattern as far as matching is concerned: it does not affect whether a value is matched, only how it is matched.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With