gpt4 book ai didi

pointers - 为什么在对取消引用的枚举进行匹配时必须使用 ref?

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

为什么我必须在 impl Keysdestruct 方法中使用 ref s 而不仅仅是 s

#[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

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