[−][src]Derive Macro amplify_derive::Display
#[derive(Display)] { // Attributes available to this derive: #[display] }
Usage
- Generate
Display
descriptions using other formatting trait:#[derive(Display, Debug)] #[display(Debug)] struct Some { /* ... */ }
- Use existing function for displaying descriptions:
Formatting function must return
#[macro_use] extern crate amplify; #[derive(Display)] #[display(Int::print)] union Int { uint: u32, int: i32 }; impl Int { pub fn print(&self) -> String { s!("Integer representation") } }
String
and take a singleself
argument (if you need formatting with streamed output, use one of existing formatting traits as shown in pt. 1). - Custom format string:
#[derive(Display)] #[display("({x}, {y})")] struct Point { x: u32, y: u32 } assert_eq!(format!("{}", Point { x: 0, y: 1 }), "(0, 1)");
- Support for alternative formatting with
alt
parameter:#[derive(Display)] #[display("({x}, {y})", alt = "{x}:{y}")] struct Point { x: u32, y: u32 } assert_eq!(format!("{}", Point { x: 0, y: 1 }), "(0, 1)"); assert_eq!(format!("{:#}", Point { x: 0, y: 1 }), "0:1");
- Use of doc comments for descrition representation. In this case doc
comments may also contain formatting like in the case 3:
You can also mix in this mode with other fors of display tags on a specific options; in this case doc comments are ignored
#[macro_use] extern crate amplify; #[derive(Display)] #[display(doc_comments)] enum Variants { /// Letter A /// Multiline comments are also working A, /// Letter B B, /// This comment is ignored #[display("Letter C")] C, /// Letter {_0} Letter(String), /// You can omit parameters and just have a normal doc comment Number(u8), /// ... for variants with named fields as well Named { some: String } }; assert_eq!(format!("{}", Variants::C), "Letter C"); assert_eq!(format!("{}", Variants::Letter(s!("K"))), " Letter K");
Example
Advanced use with enums:
#[derive(Display)] enum Test { Some, #[display("OtherName")] Other, /// Document comment working as display string Commented, Named { x: u8, }, #[display("Custom{x}", alt = "this is alternative")] NamedCustom { x: u8, }, Unnamed(u16), // NB: Use `_`-prefixed indexes for tuple values #[display("Custom{_0}")] UnnamedCustom(String), } assert_eq!(format!("{}", Test::Some), "Some"); assert_eq!(format!("{}", Test::Other), "OtherName"); assert_eq!(format!("{}", Test::Named { x: 1 }), "Named { .. }"); assert_eq!(format!("{}", Test::Unnamed(5)), "Unnamed(..)"); assert_eq!(format!("{}", Test::NamedCustom { x: 8 }), "Custom8"); assert_eq!( format!("{:#}", Test::NamedCustom { x: 8 }), "this is alternative" ); assert_eq!( format!("{}", Test::UnnamedCustom("Test".to_string())), "CustomTest" );
Use with tuple types:
#[derive(Clone, Copy, Debug, Display)] #[display("{_0}")] struct Tuple(u8);