### Auto-Generated Doc Comments Source: https://context7.com/nik-rev/displaystr/llms.txt Use `#[display(doc)]` to automatically generate documentation comments from the display strings. This ensures that display implementations and documentation remain synchronized. ```Rust use displaystr::display; #[display(doc)] pub enum HttpError { /// This doc comment will be replaced by "bad request: {_0}" BadRequest(String) = "bad request: {_0}", Unauthorized { reason: String } = "unauthorized: {reason}", NotFound = "resource not found", InternalServerError = "internal server error", } // The macro generates doc comments like: // /// bad request: {_0} // BadRequest(String), // /// unauthorized: {reason} // Unauthorized { reason: String }, // etc. fn main() { let err = HttpError::BadRequest("invalid JSON".to_string()); assert_eq!(err.to_string(), "bad request: invalid JSON"); let err = HttpError::Unauthorized { reason: "token expired".to_string() }; assert_eq!(err.to_string(), "unauthorized: token expired"); } ``` -------------------------------- ### Multiple Format Arguments with Tuple Syntax Source: https://context7.com/nik-rev/displaystr/llms.txt Use a tuple with the format string as the first element and additional expressions as subsequent elements for complex formatting. This allows for multiple arguments beyond the format string itself. ```Rust use displaystr::display; #[display] enum ProcessError { Redaction(String, Vec) = ( "the data for key `{_0}` is not available, but we recovered: {}", _1.join("+"), ), Calculation(f64, f64) = ( "calculation failed: {} (sum of {_0} and {_1})", _0 + _1, ), } fn main() { let err = ProcessError::Redaction( "secret_key".to_string(), vec!["backup1".to_string(), "backup2".to_string()], ); assert_eq!( err.to_string(), "the data for key `secret_key` is not available, but we recovered: backup1+backup2" ); let err = ProcessError::Calculation(3.5, 2.5); assert_eq!(err.to_string(), "calculation failed: 6 (sum of 3.5 and 2.5)"); } ``` -------------------------------- ### Add displaystr to Cargo.toml Source: https://github.com/nik-rev/displaystr/blob/main/README.md Add this line to your Cargo.toml file to include the displaystr crate in your project. ```toml displaystr = "0.1" ``` -------------------------------- ### Handle Multiple Arguments in Display String Source: https://github.com/nik-rev/displaystr/blob/main/README.md When a display string requires multiple arguments, use a tuple to provide them. The second element of the tuple can be an expression that evaluates to the required arguments. ```rust use displaystr::display; #[display] pub enum DataStoreError { Redaction(String, Vec) = ( "the data for key `{_0}` is not available, but we recovered: {}", _1.join("+"), ), } ``` -------------------------------- ### Generate Doc Comments with #[display(doc)] Source: https://github.com/nik-rev/displaystr/blob/main/README.md Use the `#[display(doc)]` attribute to automatically generate documentation comments for enum variants based on their display strings. ```rust use displaystr::display; #[display(doc)] pub enum DataStoreError { Disconnect(std::io::Error) = "data store disconnected", Redaction(String) = "the data for key `{_0}` is not available", InvalidHeader { expected: String, found: String, } = "invalid header (expected {expected:?}, found {found:?})", Unknown = "unknown data store error", } ``` -------------------------------- ### Expanded Display Implementation for Enum Source: https://github.com/nik-rev/displaystr/blob/main/README.md This is the code generated by the `#[display]` macro for the `DataStoreError` enum, showing the manual implementation of the `Display` trait. ```rust use displaystr::display; pub enum DataStoreError { Disconnect(std::io::Error), Redaction(String), InvalidHeader { expected: String, found: String, }, Unknown, } impl ::core::fmt::Display for DataStoreError { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { Self::Disconnect(_0) => { f.write_fmt(format_args!("data store disconnected")) } Self::Redaction(_0) => { f.write_fmt(format_args!("the data for key `{_0}` is not available")) } Self::InvalidHeader { expected, found } => { f.write_fmt(format_args!("invalid header (expected {expected}, found {found})")) } Self::Unknown => { f.write_fmt(format_args!("unknown data store error")) } } } } ``` -------------------------------- ### Expanded Display Implementation with Multiple Arguments Source: https://github.com/nik-rev/displaystr/blob/main/README.md This is the generated code for an enum variant that uses multiple arguments in its display string, demonstrating how expressions are used to format the output. ```rust use displaystr::display; pub enum DataStoreError { Redaction(String, Vec), } impl ::core::fmt::Display for DataStoreError { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { Self::Redaction(_0, _1) => f.write_fmt(format_args!( "the data for key `{_0}` is not available, but we recovered: {}", _1.join("+") )), } } } ``` -------------------------------- ### Implement Display for Enums Source: https://context7.com/nik-rev/displaystr/llms.txt Apply the #[display] attribute to an enum to define display output for various variant types using string discriminants. ```rust use displaystr::display; #[display] pub enum DataStoreError { Disconnect(std::io::Error) = "data store disconnected", Redaction(String) = "the data for key `{_0}` is not available", InvalidHeader { expected: String, found: String, } = "invalid header (expected {expected:?}, found {found:?})", Unknown = "unknown data store error", } fn main() { let error = DataStoreError::Unknown; println!("{}", error); // Output: unknown data store error let error = DataStoreError::Redaction("user_123".to_string()); println!("{}", error); // Output: the data for key `user_123` is not available let error = DataStoreError::InvalidHeader { expected: "Content-Type".to_string(), found: "Accept".to_string(), }; println!("{}", error); // Output: invalid header (expected "Content-Type", found "Accept") } ``` -------------------------------- ### Implement Display for Enum with Custom Messages Source: https://github.com/nik-rev/displaystr/blob/main/README.md Use the `#[display]` attribute macro on an enum to automatically implement the `Display` trait. Each enum variant can have a custom string literal or a formatted string. ```rust use displaystr::display; #[display] pub enum DataStoreError { Disconnect(std::io::Error) = "data store disconnected", Redaction(String) = "the data for key `{_0}` is not available", InvalidHeader { expected: String, found: String, } = "invalid header (expected {expected:?}, found {found:?})", Unknown = "unknown data store error", } ``` -------------------------------- ### Handle Unit Variants Source: https://context7.com/nik-rev/displaystr/llms.txt Use simple string discriminants for unit variants, including empty tuple and struct variants. ```rust use displaystr::display; #[display] enum Status { Active = "active", Inactive = "inactive", Pending = "pending", EmptyTuple() = "empty tuple variant", EmptyStruct {} = "empty struct variant", } fn main() { assert_eq!(Status::Active.to_string(), "active"); assert_eq!(Status::Inactive.to_string(), "inactive"); assert_eq!(Status::Pending.to_string(), "pending"); assert_eq!(Status::EmptyTuple().to_string(), "empty tuple variant"); assert_eq!(Status::EmptyStruct {}.to_string(), "empty struct variant"); } ``` -------------------------------- ### Define error enum with displaydoc Source: https://github.com/nik-rev/displaystr/blob/main/README.md Uses doc comments to define the display format for each enum variant. ```rust use thiserror::Error; use displaydoc::Display; #[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, } ``` -------------------------------- ### Expanded Enum with Auto-Generated Doc Comments Source: https://github.com/nik-rev/displaystr/blob/main/README.md This shows the enum definition after applying `#[display(doc)]`, where documentation comments are automatically added to each variant. ```rust use displaystr::display; pub enum DataStoreError { /// data store disconnected Disconnect(std::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, } // impl Display omitted since it's identical to the previous section ``` -------------------------------- ### Interpolate Struct Variant Fields Source: https://context7.com/nik-rev/displaystr/llms.txt Reference named fields directly in the format string without prefixes. ```rust use displaystr::display; #[display] enum ValidationError { InvalidRange { min: i32, max: i32, actual: i32 } = "value {actual} out of range [{min}, {max}]", MissingField { name: String } = "required field `{name}` is missing", TypeMismatch { expected: String, found: String } = "type mismatch: expected {expected:?}, found {found:?}", } fn main() { let err = ValidationError::InvalidRange { min: 0, max: 100, actual: 150 }; assert_eq!(err.to_string(), "value 150 out of range [0, 100]"); let err = ValidationError::MissingField { name: "email".to_string() }; assert_eq!(err.to_string(), "required field `email` is missing"); let err = ValidationError::TypeMismatch { expected: "string".to_string(), found: "number".to_string(), }; assert_eq!(err.to_string(), "type mismatch: expected \"string\", found \"number\""); } ``` -------------------------------- ### Integration with thiserror Source: https://context7.com/nik-rev/displaystr/llms.txt displaystr works seamlessly with thiserror for error handling. Use displaystr for Display implementation and thiserror for the Error trait and automatic `From` implementations. ```Rust use displaystr::display; use thiserror::Error; use std::io; #[derive(Error, Debug)] #[display] pub enum DatabaseError { Disconnect(#[from] io::Error) = "database connection lost", QueryFailed(String) = "query failed: {_0}", InvalidData { table: String, column: String, } = "invalid data in {table}.{column}", Timeout = "database operation timed out", } fn connect_to_db() -> Result<(), DatabaseError> { // Simulating an IO error that converts automatically via #[from] let io_err = io::Error::new(io::ErrorKind::ConnectionRefused, "connection refused"); Err(io_err)? } fn main() { match connect_to_db() { Ok(_) => println!("Connected!"), Err(e) => println!("Error: {}", e), // Output: Error: database connection lost } let err = DatabaseError::InvalidData { table: "users".to_string(), column: "email".to_string(), }; println!("Error: {}", err); // Output: Error: invalid data in users.email } ``` -------------------------------- ### Interpolate Tuple Variant Fields Source: https://context7.com/nik-rev/displaystr/llms.txt Access tuple variant fields using positional indices like _0, _1, etc., within the format string. ```rust use displaystr::display; #[display] enum ApiError { NotFound(String) = "resource `{_0}` not found", RateLimited(u32, u32) = "rate limited: {_0}/{_1} requests exceeded", Timeout(std::time::Duration) = "request timed out after {_0:?}", } fn main() { let err = ApiError::NotFound("users/42".to_string()); assert_eq!(err.to_string(), "resource `users/42` not found"); let err = ApiError::RateLimited(100, 60); assert_eq!(err.to_string(), "rate limited: 100/60 requests exceeded"); let err = ApiError::Timeout(std::time::Duration::from_secs(30)); assert_eq!(err.to_string(), "request timed out after 30s"); } ``` -------------------------------- ### Define error enum with displaystr Source: https://github.com/nik-rev/displaystr/blob/main/README.md Uses the #[display] attribute to define error messages directly within the enum variant definition. ```rust use thiserror::Error; use displaystr::display; #[derive(Error, Debug)] #[display] pub enum DataStoreError { Disconnect(#[from] io::Error) = "data store disconnected", Redaction(String) = "the data for key `{_0}` is not available", InvalidHeader { expected: String, found: String, } = "invalid header (expected {expected:?}, found {found:?})", Unknown = "unknown data store error", } ``` -------------------------------- ### Define error enum with thiserror Source: https://github.com/nik-rev/displaystr/blob/main/README.md Uses the #[error] attribute on each variant to specify the display format. ```rust use thiserror::Error; #[derive(Error, Debug)] pub enum DataStoreError { #[error("data store disconnected")] Disconnect(#[from] io::Error), #[error("the data for key `{0}` is not available")] Redaction(String), #[error("invalid header (expected {expected:?}, found {found:?})")] InvalidHeader { expected: String, found: String, }, #[error("unknown data store error")] Unknown, } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.