我有一个枚举和一个变量,
enum Message {
Write(String),
}
let msg = Message::Write("hi".to_string());
我想在“msg”中打印字符串。通过直接在 print 宏内部解构,而不使用任何额外的变量,就像这样,
print!("{Message::Write(:?)}", msg); // This won't work
或者像这样
print!("{}", msg:<Message::Write(String)>); // This won't work either
您可以根据自己的喜好打印任何复杂结构或枚举的内容,方法是实现
Display
trait。
use std::fmt;
enum Message {
Write(String),
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Message::Write(s) => write!(f, "{}", s),
}
}
}
fn main() {
let msg = Message::Write("hi".to_string());
println!("{}", msg);
}
可以通过解构打印任何复杂结构的内容:
let msg = Message::Write("hi".to_string());
println!("{}", { let Message::Write(m) = msg; m });