Rust, Software Development

Rust Display Struct Content Using Directive Or Traits

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

Rust Struct Sample – struct Person

To demonstrate an example, we need a struct. For this post, we use a struct Person that represents a real person in life. It has a surname, first name, middle name, date of birth, address, hobbies, etc. Of course, we can have more fields than these. However, for brevity, we limit the number of fields. So how do we display all these at once without going through them one by one?

Use Rust Derive Debug

To achieve our objective in Rust, we use #[derive(Debug)] on top of our Person definition to display the content of any of its instances.

However, we are only halfway to our goal. In Rust, when we want to display the content of a struct instance, we use the {:?} print marker.

Output

To Display Struct Content, Implement Display Trait

When we use #[derive(Debug)] with our struct, Rust basically implicitly implements the Debug trait. Alternatively, we can achieve the same goal by explicitly implementing the Display trait in Rust to display the content of a struct. Therefore, we could customize the way we want to display the content of a struct instance. Consider the following codes.

Then, in this case, we use another print marker – the {}, which is simpler than {:?}.

In summary, when we use the #[derive(Debug)] on a struct, we need to use the {:?} print marker. Alternatively, we can make the struct implement the Display trait. Although this translates to more Rust codes, it allows us to format the output in ways we want. And that’s how we can display the content of a struct type in Rust without explicitly printing out all the fields it has!

Tested with Rust 1.52.1.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like