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.
1 2 3 4 5 6 7 8 | #[derive(Debug)] struct Person { last_name: String, first_name: String, middle_name: String, address: String, hobbies: Vec<String> } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fn main() { let mut my_hobbies:Vec<String> = Vec::new(); my_hobbies.push("hiking".to_string()); my_hobbies.push("swimming".to_string()); let p = Person { last_name: "sg".to_string(), first_name: "karl".to_string(), middle_name: "r".to_string(), address: "Malaysia".to_string(), hobbies: my_hobbies }; println!("{:?}", p); } |
Output
1 | Person { last_name: "sg", first_name: "karl", middle_name: "r", address: "Malaysia", hobbies: ["hiking", "swimming"] } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | use std::fmt::{Display, Formatter, Result}; struct Person { last_name: String, first_name: String, middle_name: String, address: String, hobbies: Vec<String> } impl Display for Person { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "{} {} {}", self.first_name, self.middle_name, self.last_name) } } |
Then, in this case, we use another print marker – the {}, which is simpler than {:?}.
1 2 | ... println!("{}", p); |
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.