macro_rules! dformat {
($fmt: expr, $($arg: expr),*) => { ... };
}Expand description
Dynamically formats values according to a format string.
The dformat! macro provides functionality similar to Rust’s standard format! macro,
but with dynamic formatting capabilities. It uses a pre-parsed FormatString to
apply format specifications to values at runtime.
§Syntax
The macro takes two arguments:
- A reference to a
FormatStringthat has been created from a format string - A list of arguments to format
ⓘ
dformat!(format_string_ref, arg1, arg2, ...)§Examples
Basic usage:
use dyf::{FormatString, dformat};
let fmt = FormatString::from_string("Hello, {}!".to_string()).unwrap();
let result = dformat!(&fmt, "world").unwrap();
assert_eq!(result, "Hello, world!");Formatting with different specifications:
use dyf::{FormatString, dformat};
let fmt = FormatString::from_string("{:>5}, {:.2}".to_string()).unwrap();
let result = dformat!(&fmt, 42, 3.14159).unwrap();
assert_eq!(result, " 42, 3.14");Using with custom types that implement DynDisplay:
use dyf::{FormatString, dformat, DynDisplay, Error, FormatSpec};
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))
}
}
let fmt = FormatString::from_string("Point: {}".to_string()).unwrap();
let point = Point { x: 10, y: 20 };
let result = dformat!(&fmt, point).unwrap();
assert_eq!(result, "Point: Point(10, 20)");§Errors
The macro returns a Result<String, Error>. Any error might be one
of the [Error] variant.
§Performance Considerations
For best performance when formatting the same string multiple times:
- Create the
FormatStringonce and reuse it - Use the
dformat!macro for each formatting operation
use dyf::{FormatString, dformat};
let fmt = FormatString::from_string("Value: {:>10}".to_string()).unwrap();
let result1 = dformat!(&fmt, 42).unwrap();
let result2 = dformat!(&fmt, "text").unwrap();§Comparison with Standard format! Macro
While similar to Rust’s standard format! macro, dformat! provides:
- Dynamic formatting capabilities through the
DynDisplaytrait - The ability to pre-parse format strings for reuse
However, for simple cases where you don’t need these features, the standard format!
macro is recommended.