Rust 直接在 print 内部解构而不使用任何额外的变量

问题描述 投票:0回答:2

我有一个枚举和一个变量,

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
rust destructuring
2个回答
0
投票

您可以根据自己的喜好打印任何复杂结构或枚举的内容,方法是实现

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);
}

0
投票

可以通过解构打印任何复杂结构的内容:

let msg = Message::Write("hi".to_string());
println!("{}", { let Message::Write(m) = msg; m });

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.