Expand description
§format-attr
document: https://docs.rs/format-attr
A Rust proc-macro crate that provides custom derive macros for implementing Display and Debug traits with custom format strings.
§Features
DisplayAttr- Derivestd::fmt::Displaywith a custom format stringDebugAttr- Derivestd::fmt::Debugwith a custom format stringDisplayAsDebug- ImplementDisplayby delegating to the existingDebugimplementation- Support for separate format strings via
#[fmt_display(...)]and#[fmt_debug(...)] - Fallback to shared
#[fmt(...)]attribute
§Usage
Add this to your Cargo.toml:
[dependencies]
format-attr = "0.1.0"§Basic Example
use format_attr::{DisplayAttr, DebugAttr};
#[derive(DisplayAttr, DebugAttr)]
#[fmt("Point({}, {})", self.x, self.y)]
struct Point {
x: i32,
y: i32,
}
let p = Point { x: 10, y: 20 };
assert_eq!(format!("{}", p), "Point(10, 20)");
assert_eq!(format!("{:?}", p), "Point(10, 20)");§Separate Format Strings
Use #[fmt_display(...)] and #[fmt_debug(...)] for different output:
use format_attr::{DisplayAttr, DebugAttr};
#[derive(DisplayAttr, DebugAttr)]
#[fmt_display("User: {}", self.name)]
#[fmt_debug("User {{ name: {}, age: {} }}", self.name, self.age)]
struct User {
name: String,
age: u32,
}
let u = User { name: "Alice".to_string(), age: 30 };
assert_eq!(format!("{}", u), "User: Alice");
assert_eq!(format!("{:?}", u), "User { name: Alice, age: 30 }");§DisplayAsDebug
When you want Display to use the same output as Debug:
use format_attr::DisplayAsDebug;
#[derive(Debug, DisplayAsDebug)]
struct Value(i32);
let v = Value(42);
assert_eq!(format!("{}", v), "Value(42)");
assert_eq!(format!("{:?}", v), "Value(42)");§Attribute Priority
| Derive Macro | Priority 1 | Priority 2 (fallback) |
|---|---|---|
DisplayAttr | #[fmt_display(...)] | #[fmt(...)] |
DebugAttr | #[fmt_debug(...)] | #[fmt(...)] |
§License
MIT
Derive Macros§
- Debug
Attr - Derive macro for implementing
std::fmt::Debug. - Display
AsDebug - Derive macro for implementing
std::fmt::Displayusing the existingDebugimplementation. - Display
Attr - Derive macro for implementing
std::fmt::Display.