匹配枚举引用的语法是什么? [英] What is the syntax to match on a reference to an enum?

查看:43
本文介绍了匹配枚举引用的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎每个 Rust 的枚举类型的介绍性文档解释了如何在您的枚举对象上匹配拥有,但是如果您不拥有枚举对象,而您只有一个要与之匹配的引用呢?我不知道语法是什么.

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);
}

Rust Playground 在尝试编译时匹配的前两种情况:

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?

推荐答案

从 Rust 1.26 开始,惯用的方式是你最初编写它的方式 因为match 人体工程学得到了改进:

As of Rust 1.26, the idiomatic way is 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);
}

这篇关于匹配枚举引用的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆