对枚举的引用要匹配的语法是什么?

问题描述 投票:35回答:3

似乎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`

如何更改该代码以进行编译?我尝试在许多不同的地方添加&符,但没有任何运气。甚至可以匹配对枚举的引用吗?

rust
3个回答
19
投票
从Rust 1.26开始,惯用的方式是

您最初编写的方式 because match ergonomics have been improved

match

26
投票

编辑:请参阅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"),
}
而不是_使“未使用”警告静音。    

12
投票
由于有用的编译器消息,我知道了:

ref c

© www.soinside.com 2019 - 2024. All rights reserved.