枚举方法未打印出预期的值

huangapple go评论57阅读模式
英文:

enum method not printing out the expected value

问题

以下是翻译好的部分:

"Could somone point out what I am doing wrong here? Why isn't the call() method printing the value of self, which should be hello?"

"有人能指出我在这里做错了什么吗?为什么call()方法不打印self的值,它应该是hello?"

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

impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    let m = Message::Write(String::from("Hello"));
    m.call();
}

请注意,代码中的HTML转义字符已被移除。

英文:

Could somone point out what I am doing wrong here? Why isn't the call() method printing the value of self, which should be hello?

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}
impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}


fn main() {
    let m = Message::Write(String::from("Hello"));
    m.call();
  
}

答案1

得分: 3

Message 类型必须实现 Debug 特性,以提供 {:?}{:#?} 格式化支持。可以使用 derive 属性宏来完成它。

#[derive(Debug)]
enum Message {
    ...
}

// 另一种方式是手动实现
impl Debug for Message {
    ...
}
英文:

Message type must implement the Debug trait which brings {:?} and {:#?} formatting support. It can be done with the help of the derive attribute macro.

#[derive(Debug)]
enum Message {
    ...
}

// the other way is a manual implementation
impl Debug for Message {
    ...
}

huangapple
  • 本文由 发表于 2023年6月2日 06:12:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定