Rust's enum types的每一篇介绍性文档似乎都解释了如何在您所创建的枚举对象上创建match,但是如果您不拥有该枚举对象,并且只拥有一个要匹配的引用,该怎么办?我不知道语法是什么.
下面是我试图匹配枚举引用的一些代码:
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);
}
在try 编译时,Rust Playground给出了匹配的前两种情况下的错误:
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`
我怎样才能修改代码来编译它呢?我试着在很多不同的地方添加了符号,但没有成功.甚至可以匹配对枚举的引用吗?