Recursively print a structure in `fmt :: Display`

I am currently implementing fmt::Display

for the struct to print to the console. However, the structure has a field that is of Vec

this type.

Struct

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

      

Current fmt :: Show (invalid)

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

      

Desired exit

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

      

+3


source to share


2 answers


There is a (somewhat hidden) function Debug

, you can use the format specifier {:#?}

to print your object nicely (indented and multiple lines). If you rewrite your struct members in the same order as your requested output and get Debug

trait

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

      

then your output might look like:



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

      

Try it on PlayPen

+5


source


You seem to be confusing Display

and Debug

.

{:?}

uses the property Debug

for formatting. You probably didn't implement Debug

in your type, so you'll get an error. To use a characteristic Display

, write {}

in the format string.



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

      

+4


source







All Articles