在`fmt :: Display`中递归打印struct

时间:2015-06-27 01:45:18

标签: struct console rust println

我目前正在为一个结构体实现fmt::Display,以便它将打印到控制台。但是结构有一个字段,它是Vec的类型。

STRUCT

pub struct Node<'a> {
    pub start_tag: &'a str,
    pub end_tag: &'a str,
    pub content: String,
    pub children: Vec<Node<'a>>,
}

当前fmt ::显示(无效)

impl<'a> fmt::Display for Node<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "START TAG: {:?}", self.start_tag);
        write!(f, "CONTENT: {:?}", self.content);
        for node in self.children {
            write!(f, "CHILDREN:\n\t {:?}", node);
        }
        write!(f, "END TAG: {:?}", self.end_tag);
    }
}

期望输出

START TAG: "Hello"
CONTENT: ""
CHILDREN:
   PRINTS CHILDREN WITH INDENT
END TAG: "World"

2 个答案:

答案 0 :(得分:5)

Debug有一个(有些隐藏的)功能,您可以使用格式说明符{:#?}来漂亮打印您的对象(使用缩进和多行)。如果您重写struct的元素以使其与请求的输出具有相同的顺序并导出Debug特征

#[derive(Debug)]
pub struct Node<'a> {
    pub start_tag: &'a str,
    pub content: String,
    pub children: Vec<Node<'a>>,
    pub end_tag: &'a str,
}

然后你的输出看起来像这样:

Node {
    start_tag: "Hello",
    content: "",
    children: [
        Node {
            start_tag: "Foo",
            content: "",
            children: [],
            end_tag: "Bar"
        }
    ],
    end_tag: "World"
}

PlayPen

中试用

答案 1 :(得分:4)

您似乎对DisplayDebug感到困惑。

{:?}使用Debug特征进行格式化。您可能没有在类型上实现Debug,这就是您收到错误的原因。要使用Display特征,请在格式字符串中写下{}

write!(f, "CHILDREN:\n\t {}", node);