On this page
Display
Prev: error_and_fmt | Up: error_and_fmt | Next: `Error`
Rel: error_and_fmt, rust/builtins
Ref: Rust std — Display
Tags: #public #prog #rust #stdlib #error_and_fmt #tier/core
Signature & Overview
trait Display { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result; }
User-facing formatting ({}); implementing Display automatically implements .to_string().
Notes & Pitfalls
- User-facing formatting (
{}and.to_string()): ImplementingDisplayautomatically gives your type.to_string()viaToString. - Distinct from
Debug({:?}): Derive#[derive(Debug)]for developer diagnostics; implementDisplaymanually for clean human output.
Example
use std::fmt;
struct Version(u8, u8, u8);
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "v{}.{}.{}", self.0, self.1, self.2)
}
}
fn main() {
assert_eq!(Version(1, 2, 0).to_string(), "v1.2.0");
}
Linked from
Related notes
- tuts/rust/std/error_and_fmt/Error Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/format shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/ffi/CString shared tags: #prog, #rust, #stdlib, #tier