我目前正在为一个结构体实现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>>,
}
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"
答案 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"
}
中试用
答案 1 :(得分:4)