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`

我怎样才能修改代码来编译它呢?我试着在很多不同的地方添加了符号,但没有成功.甚至可以匹配对枚举的引用吗?

推荐答案

从Rust 1.26开始,惯用的方式是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);
}

Rust相关问答推荐

使用windows crate Rust 展示windows

在一个tauri协议处理程序中调用一个rectuc函数的推荐技术是什么?

为什么幻影数据不能自动推断?

如何将元素添加到向量并返回对该元素的引用?

在函数内定义impl和在函数外定义impl的区别

如何删除Mac Tauri上的停靠图标?

如何将映射反序列化为具有与键匹配的字段的定制 struct 的向量?

获取与父字符串相关的&;str的原始片段

解析程序无法在Cargo 发布中 Select 依赖版本

如何将带有嵌套borrow /NLL 的 Rust 代码提取到函数中

.to_owned()、.clone() 和取消引用 (*) 之间有区别吗?

Rust 1.70 中未找到 Trait 实现

更新 rust ndarray 中矩阵的一行

Rust 异步循环函数阻塞了其他future 任务的执行

Rust中的标记特征是什么?

打印 `format_args!` 时borrow 时临时值丢失

哪些特征通过 `Deref` 而哪些不通过?

第 7.4 章片段中如何定义 `thread_rng`

如何用另一个变量向量置换 rust simd 向量?

A 有一个函数,它在 Option<> 类型中时无法编译,但在 Option<> 类型之外会自行编译.为什么?