似乎Rust的枚举类型的每个介绍性文档都解释了如何匹配您拥有的枚举对象,但是如果您不拥有枚举对象并且您只是想要匹配它的引用呢?我不知道语法是什么.
以下是我尝试匹配枚举引用的一些代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
在尝试编译时,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: …Run Code Online (Sandbox Code Playgroud) 我在理解refRust中的模式时遇到了问题.我指的是https://rustbyexample.com/scope/borrow/ref.html
这是我不明白的代码:
let point = Point { x: 0, y: 0 };
let _copy_of_x = {
// `ref_to_x` is a reference to the `x` field of `point`
let Point { x: ref ref_to_x, y: _ } = point;
// Return a copy of the `x` field of `point`
*ref_to_x
};
Run Code Online (Sandbox Code Playgroud)
我得到的是最后一个let表达式(?)是某种模式匹配.所以我的理解ref ref_to_x应该等于原始0的x价值point.
但我不明白ref实际上是做什么的.当我添加这样的代码时:
println!("x: {}", point.x);
println!("ref_to_x: {}", ref_to_x);
println!("*ref_to_x: {}", *ref_to_x);
Run Code Online (Sandbox Code Playgroud)
我总是得到0,所以似乎没有区别.不知何故,我希望 …
我想将my_id,仅当存在时更改为另一个值:
fn read(id: &mut i32) {
*id = 42;
}
struct S {
my_id: Option<i32>,
}
impl S {
fn run(&mut self) {
match self.my_id {
Some(mut id) => read(&mut id),
_ => (),
}
}
}
fn main() {
let mut s = S { my_id: 0.into() };
s.run();
println!("{:?}", s.my_id);
}
Run Code Online (Sandbox Code Playgroud)
此代码打印Some(0),这意味着替换失败,但我不明白为什么。我是否因为模式匹配而失去了可变性?
Rust的书称ref关键词为“传统”。当我想遵循隐式建议避免时ref,如何在以下玩具示例中做到这一点?您也可以在操场上找到代码。
struct OwnBox(i32);
impl OwnBox {
fn ref_mut(&mut self) -> &mut i32 {
match *self {
OwnBox(ref mut i) => i,
}
// This doesn't work. -- Even not, if the signature of the signature of the function is
// adapted to take an explcit lifetime 'a and use it here like `&'a mut i`.
// match *self {
// OwnBox(mut i) => &mut i,
// }
// This doesn't work
// …Run Code Online (Sandbox Code Playgroud) use crate::List::{Cons, Nil};
#[derive(Debug)]
struct Foo {}
#[derive(Debug)]
enum List {
Cons(i32, Foo),
Nil,
}
impl List {
fn tail(&self) -> Option<&Foo> {
match self {
Cons(_, item) => Some(item), // why `item` is of type `&Foo`?
Nil => None,
}
}
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述,为什么是item类型&Foo?说的item是类型&Foo而不是类型的规则是什么Foo?
我理解项目是没有意义的Foo; &self表示self引用是参考,因此将值从引用中移出是没有意义的,但是是否有任何明确定义规则的规范?