pub trait DynDisplay {
// Required method
fn dyn_fmt(&self, f: &FormatSpec) -> Result<String, Error>;
}Expand description
A trait for dynamic display formatting.
This trait provides a way to implement custom formatting for types that need to support
dynamic format specifications at runtime. It’s similar to the standard std::fmt::Display trait
but with additional formatting control through FormatSpec.
§Examples
Basic implementation for a custom type:
use dyf::{DynDisplay, FormatSpec, Error};
struct Point {
x: i32,
y: i32,
}
impl DynDisplay for Point {
fn dyn_fmt(&self, spec: &FormatSpec) -> Result<String, Error> {
let s = format!("Point({}, {})", self.x, self.y);
Ok(spec.fill_and_align(s, dyf::Align::Left))
}
}Implementation with format-aware behavior:
use dyf::{DynDisplay, FormatSpec, Error, FmtType};
struct Color {
r: u8,
g: u8,
b: u8,
}
impl DynDisplay for Color {
fn dyn_fmt(&self, spec: &FormatSpec) -> Result<String, Error> {
match spec.ty {
FmtType::LowerHex => Ok(format!(
"#{:02x}{:02x}{:02x}",
self.r, self.g, self.b
)),
FmtType::UpperHex => Ok(format!(
"#{:02X}{:02X}{:02X}",
self.r, self.g, self.b
)),
FmtType::Debug => Ok(format!(
"Color {{ r: {}, g: {}, b: {} }}",
self.r, self.g, self.b
)),
_ => Ok(format!(
"RGB({}, {}, {})",
self.r, self.g, self.b
)),
}.map(|s| spec.fill_and_align(s, dyf::Align::Left))
}
}Required Methods§
Sourcefn dyn_fmt(&self, f: &FormatSpec) -> Result<String, Error>
fn dyn_fmt(&self, f: &FormatSpec) -> Result<String, Error>
Formats the value using the given format specification.
§Arguments
spec- The format specification containing alignment, width, precision, and other formatting options
§Returns
A Result containing the formatted string or an error if formatting fails.
§Errors
This function may return an error if the format specification is not supported for this type or if formatting fails for other reasons.