pointers - 为什么在取消引用的枚举上匹配时必须使用 ref ?
问题描述
为什么我必须使用ref s
而不仅仅是s
在destruct
方法中impl Keys
?
#[derive(Debug)]
enum Direction {
Up(Point),
Down(Point),
Right(Point),
Left(Point),
}
#[derive(Debug)]
struct Point {
x: u32,
y: u32,
}
#[derive(Debug)]
enum Keys {
Up_key(String),
Down_key(String),
Right_key(String),
Left_key(String),
}
impl Direction {
fn match_direction(&self) -> Keys {
match *self {
Direction::Up(_) => Keys::Up_key(String::from("Up key is pressed")),
Direction::Down(_) => Keys::Down_key(String::from("Down key is pressed")),
Direction::Right(_) => Keys::Right_key(String::from("Right key is pressed")),
Direction::Left(_) => Keys::Left_key(String::from("Left key is pressed")),
}
}
}
impl Keys {
fn destruct(&self) -> &String {
match *self {
Keys::Up_key(ref s) => s,
Keys::Down_key(ref s) => s,
Keys::Left_key(ref s) => s,
Keys::Right_key(ref s) => s,
}
}
}
fn main() {
let test_1 = Direction::Right(Point { x: 1, y: 0 });
let x = test_1.match_direction();
println!("{:#?}", x);
let k = x.destruct();
println!("{}", k);
}
输出:
Right_key(
"Right key is pressed",
)
Right key is pressed
解决方案
使用ref
可防止模式匹配获取s
.
推荐阅读
- flutter - Flutter:为什么内容替换List中的值而不是添加到List中?
- c# - LINQ 查询结果中的奇怪值
- python - TypeError:调用 pd.to_numeric 时字符串索引必须是整数
- swift - 转动手腕时流暂停 - watchOS / Swift
- algorithm - 筏领导选举算法中的TermId?
- android - 为什么 gradle 不实现 com.android.support:design:28.0.0 来添加 TextInputLayout?
- jquery - 如何将 txt 数据作为选项值和选项标记填充到选择标记中
- python - 根据分隔符拆分字符串列并为 Pyspark 中的每个值创建列
- spring - 使用由资源服务器客户端密钥和秘密生成的令牌授予对资源服务器的访问权限 - Spring boot
- c# - WPF中的树视图和组合框之间没有发生两种方式绑定