0

Rust – How to Display the Contents of Struct

Last Updated on

In Rust, we can display the contents of a struct type without explicitly printing out all the fields it has.

A struct Person

A struct Person represents a real person in life. It has a surname, first name, middle name, date of birth, address, hobbies and etc. I can have more than fields than we can imagine. So how do we display all these at once without going through one by one?

Derive Debug

To achieve our objective, we use #[derive(Debug)]  on top of our Person definition.

When we want to display the struct instance’s content, we use {:?} print marker.

Output

Implement Display Trait

Alternatively, we can implement the Display trait for a struct. With this, we do not have to derive the Debug trait.

Then, we use another print marker – the {}.

Tested with Rust 1.44.1.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer