gpt4 book ai didi

rust - 匹配枚举引用的语法是什么?

转载 作者:行者123 更新时间:2023-11-29 08:33:25 24 4
gpt4 key购买 nike

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

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 开始,惯用的方式是您最初编写它的方式 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 - 匹配枚举引用的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40073084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com