如何在Rust中访问方法内部的元组枚举的参数

大提琴手

在以下代码中,如何访问字符串"hello"(定义时传递的字符串m)?

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

impl Message {
    fn call(&self) {
        // How to access "hello" string from here?
    }
}

let m = Message::Write(String::from("hello"));
m.call();
丹尼尔·法斯

由于enum Message可以处于多种状态,因此您必须处于正确的状态才能提取问候。

fn call(&self) {
   match self {
      Message::Write(string) => println!("{}", string),
      _ => {},
   }
}

锈操场链接

编辑:user4815162342解决方案也是正确的,您可以使用matchif let互换使用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章