Rust E0277: type doesn't implement Display
Rust reports E0277 when code requires a trait that the type does not implement. With {} formatting, the required trait is std::fmt::Display.
struct Info {
name: &'static str,
}
fn main() {
let info = Info { name: "Ada" };
println!("{info}");
}The example above is intentionally rejected by the stable Rust compiler in CI.
Fix it by implementing Display
Section titled “Fix it by implementing Display”If the type is yours and {} should produce a deliberate user-facing representation, implement Display for it.
pub struct DisplayInfo {
pub name: &'static str,
}
impl fmt::Display for DisplayInfo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.name)
}
}Display::fmt writes the representation into the supplied Formatter and returns fmt::Result. Once the type implements Display, the same representation also powers .to_string().
For the implementation pattern in more detail, see implement Display for a Rust struct.
Do you actually want Debug instead?
Section titled “Do you actually want Debug instead?”{} and {:?} are not interchangeable spellings of the same formatter. {} requests Display, which is intended for a deliberate user-facing representation. {:?} requests Debug, which is intended for programmer-facing inspection.
If you only need to inspect your own struct while developing, deriving Debug and using {:?} may be the appropriate choice. See Debug vs Display before changing the format specifier just to make the error disappear.
Why E0277 appears here
Section titled “Why E0277 appears here”E0277 is broader than formatting. It means a required trait bound is missing. In this case the formatting placeholder creates that requirement: {} needs Display, so a type without Display cannot be passed to that formatting position.
If the compiler instead says the type does not implement Debug, see E0277: type doesn’t implement Debug.