在 `fmt::Display` 中递归打印结构

Recursively print struct in `fmt::Display`

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

结构

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

当前fmt::Display(无效)

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"

看来你很困惑 Display and Debug

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

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

Debug 有一个(有点隐藏的)功能,您可以使用格式说明符 {:#?} 来漂亮地打印您的对象(缩进和多行)。如果您重写结构的元素以与您请求的输出具有相同的顺序并派生 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

中试用