Implement Display Trait
Write a Rust implementation of the Display trait for a Person struct with name: String and age: i32 fields. The Display trait controls how a value is formatted with the {} placeholder in println!, format!, and other formatting macros. The output format should be "Person: {name} ({age})".
The Display trait is one of Rust's most important traits. It is defined in std::fmt and requires implementing the fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> method. The write! macro within the method writes formatted output to the provided Formatter. Implementing Display enables a type to be used with println! and to_string().
Unlike Debug (which uses {:?}), Display is for user-facing output and must be explicitly implemented for each type. The Rust compiler does not provide a default Display implementation. This is because Display is expected to produce human-readable output that makes sense for the specific type's domain.
Time complexity is O(n) where n is the string length of the formatted output. Space complexity is O(k) where k is the formatted string size. The write! macro writes directly to the formatter's internal buffer without intermediate allocation.
Edge cases include empty names, long names, special characters in names, and ensuring the method signature uses std::fmt::Result as the return type.
Example Input & Output
Another person
Display format shows name and age
Final example
Different person
Yet another
Algorithm Flow

Solution Approach
Best Answers
use std::fmt;
struct Person {
name: String,
age: i32,
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Person: {} ({})", self.name, self.age)
}
}
fn solution(name: String, age: i32) -> String {
let p = Person { name, age };
format!("{}", p)
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
