【问题标题】:Why do I have to use ref when matching on a dereferenced enum? [duplicate]为什么在取消引用的枚举上匹配时必须使用 ref ? [复制]
【发布时间】:2019-10-16 09:34:33
【问题描述】:

为什么我必须在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

【问题讨论】:

  • 您可以改用match self { Keys::Up_key(s)

标签: pointers rust ref


【解决方案1】:

使用ref 可防止模式匹配获取s 的所有权。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2019-10-06
    • 1970-01-01
    • 2011-02-25
    • 2016-06-25
    • 2015-12-10
    • 2013-01-31
    相关资源
    最近更新 更多