### Struct Display Implementation with displaydoc Source: https://context7.com/yaahc/displaydoc/llms.txt Shows how to implement `fmt::Display` for structs using `#[derive(Display)]`. Supports generic parameters and interpolation of struct fields. ```rust use displaydoc::Display; // Basic struct with field interpolation /// oh no, an error: {0} #[derive(Display)] pub struct Error(pub E); // Struct with named fields /// Just a basic struct with message: {thing} #[derive(Display)] struct HappyStruct { thing: &'static str, } fn main() { // Generic struct - E doesn't need Display bound on definition let error: Error<&str> = Error("something went wrong"); assert_eq!(format!("{}", error), "oh no, an error: something went wrong"); // With different types let numeric_error: Error = Error(42); assert_eq!(format!("{}", numeric_error), "oh no, an error: 42"); // Named field struct let happy = HappyStruct { thing: "hello world" }; assert_eq!(format!("{}", happy), "Just a basic struct with message: hello world"); } ``` -------------------------------- ### No_std support Source: https://context7.com/yaahc/displaydoc/llms.txt Configure displaydoc for no_std environments by disabling default features in Cargo.toml. ```toml # Cargo.toml for no_std usage [dependencies] displaydoc = { version = "0.2", default-features = false } ``` ```rust #![no_std] use displaydoc::Display; #[derive(Display)] /// Just a basic struct {thing} struct HappyStruct { thing: &'static str, } #[derive(Display)] enum NoStdError { /// I really like Variant1 Variant1, /// Variant2 with value {0} Variant2(u32), /// Variant3 is okay {sometimes} Variant3 { sometimes: &'static str }, } // These types implement core::fmt::Display and work in no_std ``` -------------------------------- ### Path and PathBuf support Source: https://context7.com/yaahc/displaydoc/llms.txt Displaydoc automatically formats Path and PathBuf types using their .display() method. ```rust use displaydoc::Display; use std::path::PathBuf; #[derive(Display)] enum FileError { /// The path {0} was not found NotFound(PathBuf), /// Cannot read file at {path} ReadError { path: PathBuf }, } fn main() { let err1 = FileError::NotFound(PathBuf::from("/var/log/app.log")); assert_eq!(format!("{}", err1), "The path /var/log/app.log was not found"); let err2 = FileError::ReadError { path: PathBuf::from("/etc/config.yaml"), }; assert_eq!(format!("{}", err2), "Cannot read file at /etc/config.yaml"); } ``` -------------------------------- ### Enum Display Derive with displaydoc Source: https://context7.com/yaahc/displaydoc/llms.txt Demonstrates implementing `fmt::Display` for an enum using the `#[derive(Display)]` macro. Supports static messages, positional parameters (`{0}`), and named fields with debug formatting (`{:?}`). ```rust use displaydoc::Display; // Basic enum with Display derive #[derive(Display, Debug)] pub enum DataStoreError { /// data store disconnected Disconnect, /// the data for key `{0}` is not available Redaction(String), /// invalid header (expected {expected:?}, found {found:?}) InvalidHeader { expected: String, found: String, }, /// unknown data store error Unknown, } fn main() { // Simple variant with static message let err1 = DataStoreError::Disconnect; assert_eq!(format!("{}", err1), "data store disconnected"); // Positional parameter interpolation with {0} let err2 = DataStoreError::Redaction("SECRET_KEY".to_string()); assert_eq!(format!("{}", err2), "the data for key `SECRET_KEY` is not available"); // Named fields with debug formatting {:?} let err3 = DataStoreError::InvalidHeader { expected: "application/json".to_string(), found: "text/plain".to_string(), }; assert_eq!( format!("{}", err3), "invalid header (expected \"application/json\", found \"text/plain\")" ); // Static message variant let err4 = DataStoreError::Unknown; assert_eq!(format!("{}", err4), "unknown data store error"); } ``` -------------------------------- ### Add displaydoc to Cargo.toml Source: https://github.com/yaahc/displaydoc/blob/master/README.md Add the displaydoc crate as a dependency in your Cargo.toml file. Requires rustc 1.56 or later. ```toml [dependencies] displaydoc = "0.2" ``` -------------------------------- ### Block doc comments support Source: https://context7.com/yaahc/displaydoc/llms.txt Use block doc comments (/** */) to include multi-paragraph documentation without triggering errors. ```rust use displaydoc::Display; #[derive(Display)] enum MultiLineVariants { /** * Variant4 wants to have a lot of lines * * Lets see how this works out for it */ Variant4, /** what happens if we * put text on the first line? */ Variant5, /** what happens if we don't use *? */ Variant6, } fn main() { // Block comments preserve newlines and paragraphs let v4 = MultiLineVariants::Variant4; assert_eq!( format!("{}", v4), "Variant4 wants to have a lot of lines\n\nLets see how this works out for it" ); // Text on first line works too let v5 = MultiLineVariants::Variant5; assert_eq!(format!("{}", v5), "what happens if we\nput text on the first line?"); // Without asterisks let v6 = MultiLineVariants::Variant6; assert_eq!(format!("{}", v6), "what happens if we don't use *?"); } ``` -------------------------------- ### Implement Error Handling with displaydoc and thiserror Source: https://context7.com/yaahc/displaydoc/llms.txt Demonstrates defining an error enum with displaydoc for Display and thiserror for Error, including source chaining and field interpolation. ```rust use std::io; use displaydoc::Display; use thiserror::Error; #[derive(Display, Error, Debug)] pub enum DataStoreError { /// data store disconnected Disconnect(#[source] io::Error), /// the data for key `{0}` is not available Redaction(String), /// invalid header (expected {expected:?}, found {found:?}) InvalidHeader { expected: String, found: String, }, /// unknown data store error Unknown, } fn fetch_data(key: &str) -> Result { // Simulate various errors if key == "secret" { return Err(DataStoreError::Redaction(key.to_string())); } if key == "invalid" { return Err(DataStoreError::InvalidHeader { expected: "v2".to_string(), found: "v1".to_string(), }); } Ok(format!("data for {}", key)) } fn main() { match fetch_data("secret") { Ok(data) => println!("Got: {}", data), Err(e) => { // Display trait from displaydoc provides human-readable message println!("Error: {}", e); // Output: Error: the data for key `secret` is not available } } match fetch_data("invalid") { Ok(data) => println!("Got: {}", data), Err(e) => { println!("Error: {}", e); // Output: Error: invalid header (expected "v2", found "v1") } } } ``` -------------------------------- ### Derive Display for a Generic Struct Source: https://github.com/yaahc/displaydoc/blob/master/README.md Implement `Display` for a generic struct using `displaydoc`. The doc comment on the struct defines the display output, interpolating fields using `{0}` syntax. ```rust /// oh no, an error: {0} #[derive(Display)] pub struct Error(pub E); let error: Error<&str> = Error("muahaha i am an error"); assert!("oh no, an error: muahaha i am an error" == &format!("{}", error)); ``` -------------------------------- ### Override Display String with #[displaydoc("...")] Source: https://context7.com/yaahc/displaydoc/llms.txt Illustrates using the `#[displaydoc("...")]` attribute to override doc comments for `fmt::Display` implementations. This is useful for custom display strings or when doc comments are not suitable for output. ```rust use displaydoc::Display; #[derive(Display, Debug)] pub enum ApiError { /// This documentation explains the error for developers /// and can span multiple lines with detailed information. #[displaydoc("request failed with status {0}")] /// More documentation that will also be ignored HttpError(u16), /// Internal documentation #[displaydoc("connection timeout after {seconds} seconds")] Timeout { seconds: u32, }, } fn main() { // The displaydoc attribute takes precedence over doc comments let http_err = ApiError::HttpError(404); assert_eq!(format!("{}", http_err), "request failed with status 404"); let timeout_err = ApiError::Timeout { seconds: 30 }; assert_eq!(format!("{}", timeout_err), "connection timeout after 30 seconds"); } ``` -------------------------------- ### Derive Display for Error Enum with thiserror Source: https://github.com/yaahc/displaydoc/blob/master/README.md Implement `Display` for an enum using `displaydoc` alongside `thiserror` for error handling. Doc comments on variants define the display output, interpolating fields using `{var}` or `{0}` syntax. Source error locations are handled via `#[source]`. ```rust use std::io; use displaydoc::Display; use thiserror::Error; #[derive(Display, Error, Debug)] pub enum DataStoreError { /// data store disconnected Disconnect(#[source] io::Error), /// the data for key `{0}` is not available Redaction(String), /// invalid header (expected {expected:?}, found {found:?}) InvalidHeader { expected: String, found: String, }, /// unknown data store error Unknown, } let error = DataStoreError::Redaction("CLASSIFIED CONTENT".to_string()); assert!("the data for key `CLASSIFIED CONTENT` is not available" == &format!("{}", error)); ``` -------------------------------- ### Prefix enum doc attributes Source: https://context7.com/yaahc/displaydoc/llms.txt The #[prefix_enum_doc_attributes] attribute prepends the enum's doc comment to each variant's message. ```rust use displaydoc::Display; /// this type is pretty swell #[derive(Display)] #[prefix_enum_doc_attributes] enum TestType { /// this variant is too Variant1, /// this variant is two Variant2, } fn main() { // The enum's doc comment is prefixed to each variant let v1 = TestType::Variant1; assert_eq!(format!("{}", v1), "this type is pretty swell: this variant is too"); let v2 = TestType::Variant2; assert_eq!(format!("{}", v2), "this type is pretty swell: this variant is two"); } ``` -------------------------------- ### Ignore extra doc attributes Source: https://context7.com/yaahc/displaydoc/llms.txt Use the #[ignore_extra_doc_attributes] attribute to prevent paragraph breaks in doc comments from causing compile errors. ```rust use displaydoc::Display; // Without the attribute, paragraph breaks cause compile errors // With the attribute, only content before the break is used #[derive(Display)] #[ignore_extra_doc_attributes] /// multi line error message /// continues here /// /// this paragraph is ignored for Display /// additional documentation for developers only struct IgnoredParagraphs; // Multi-line doc that gets combined (no paragraph break) #[derive(Display)] #[ignore_extra_doc_attributes] /// Just a basic struct {thing} /// and this line is included too struct HappyStruct2 { thing: &'static str, } fn main() { let ignored = IgnoredParagraphs; assert_eq!(format!("{}", ignored), "multi line error message continues here"); let happy = HappyStruct2 { thing: "test" }; assert_eq!(format!("{}", happy), "Just a basic struct test and this line is included too"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.