似乎Rust的enum types的每个介绍性文档都说明了如何对您own的枚举对象进行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);
}
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`
如何更改该代码以进行编译?我尝试在许多不同的地方添加&符,但没有任何运气。甚至可以匹配对枚举的引用吗?
您最初编写的方式 because match
ergonomics have been improved:
match
编辑:请参阅Shepmaster的最新习语答案
惯用的方式是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);
}
您可以使用match *self { Animal::Cat(ref c) => f.write_str("c"), Animal::Dog => f.write_str("d"), }
而不是_
使“未使用”警告静音。
ref c