### Example Usage Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/try_unwrap.md Demonstrates how to use the generated `try_unwrap` methods, including handling successful unwraps and errors when the wrong variant is encountered. ```APIDOC ## Example Usage ```rust # use derive_more::TryUnwrap; # # #[derive(Debug, PartialEq)] #[derive(TryUnwrap)] #[try_unwrap(owned, ref, ref_mut)] enum Maybe { Nothing, Just(T), } fn main() { assert_eq!(Maybe::Just(1).try_unwrap_just(), Ok(1)); // Unlike `Unwrap`, it does not panic. assert_eq!( Maybe::<()>::Nothing.try_unwrap_just().map_err(|err| err.input), Err(Maybe::<()>::Nothing), // and the value is returned! ); assert_eq!( Maybe::Just(2).try_unwrap_nothing().map_err(|err| err.input), Err(Maybe::Just(2)), ); assert_eq!( Maybe::<()>::Nothing.try_unwrap_just().map_err(|err| err.to_string()), Err("Attempt to call `Maybe::try_unwrap_just()` on a `Maybe::Nothing` value".into()), ); assert_eq!((&Maybe::Just(42)).try_unwrap_just_ref(), Ok(&42)); assert_eq!((&mut Maybe::Just(42)).try_unwrap_just_mut(), Ok(&mut 42)); } ``` ``` -------------------------------- ### Rust 2015 Edition Setup Source: https://github.com/jeltef/derive_more/blob/master/README.md For projects using the Rust 2015 edition, use `extern crate` and `#[macro_use]` directives. ```rust extern crate core; #[macro_use] extern crate derive_more; # fn main() {} // omit wrapping statements above into `main()` in tests ``` -------------------------------- ### Sum Example Usage Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/sum.md Demonstrates summing a vector of MyInts using the derived Sum trait. Requires the Add trait to be derived as well. ```rust # use derive_more::{Add, Sum}; # #[derive(Add, Sum, PartialEq)] struct MyInts(i32, i64); let int_vec = vec![MyInts(2, 3), MyInts(4, 5), MyInts(6, 7)]; assert!(MyInts(12, 15) == int_vec.into_iter().sum()); ``` -------------------------------- ### Derive Unwrap Example Usage Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/unwrap.md Demonstrates how to use #[derive(Unwrap)] with options for owned, ref, and ref_mut access. Panics occur if the wrong variant is unwrapped. ```rust use derive_more::Unwrap; #[derive(Unwrap)] #[unwrap(owned, ref, ref_mut)] enum Maybe { Just(T), Nothing, } fn main() { assert_eq!(Maybe::Just(1).unwrap_just(), 1); // Panics if variants are different // assert_eq!(Maybe::<()>::Nothing.unwrap_just(), /* panic */); // assert_eq!(Maybe::Just(2).unwrap_nothing(), /* panic */); assert_eq!((&Maybe::Just(42)).unwrap_just_ref(), &42); assert_eq!((&mut Maybe::Just(42)).unwrap_just_mut(), &mut 42); } ``` -------------------------------- ### Example Usage of derive_more::From Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/from.md Demonstrates various use cases of `#[derive(From)]`, including simple conversions, forwarding implementations, ignoring variants, and specifying additional conversions. ```rust use derive_more::From; // Allow converting from i32 #[derive(From, PartialEq)] struct MyInt(i32); // Forward from call to the field, so allow converting // from anything that can be converted into an i64 (so most integers) #[derive(From, PartialEq)] #[from(forward)] struct MyInt64(i64); // You can ignore a variant #[derive(From, PartialEq)] enum MyEnum { SmallInt(i32), NamedBigInt { int: i64 }, #[from(ignore)] NoFromImpl(i64), } // Or explicitly annotate the ones you need #[derive(From, PartialEq)] enum MyEnum2 { #[from] SmallInt(i32), #[from] NamedBigInt { int: i64 }, NoFromImpl(i64), } // And even specify additional conversions for them #[derive(From, PartialEq)] enum MyEnum3 { #[from(i8, i32)] SmallInt(i32), #[from(i16, i64)] NamedBigInt { int: i64 }, NoFromImpl(i64), } assert!(MyInt(2) == 2.into()); assert!(MyInt64(6) == 6u8.into()); assert!(MyEnum::SmallInt(123) == 123i32.into()); assert!(MyEnum::SmallInt(123) != 123i64.into()); assert!(MyEnum::NamedBigInt{int: 123} == 123i64.into()); assert!(MyEnum3::SmallInt(123) == 123i8.into()); assert!(MyEnum3::NamedBigInt{int: 123} == 123i16.into()); ``` -------------------------------- ### Example Usage of TryUnwrap Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/try_unwrap.md Demonstrates how to use the TryUnwrap derive macro with owned, ref, and ref_mut options. It shows successful unwraps and how errors are handled without panics, returning the original value. ```rust use derive_more::TryUnwrap; #[derive(Debug, PartialEq)] #[derive(TryUnwrap)] #[try_unwrap(owned, ref, ref_mut)] enum Maybe { Nothing, Just(T), } fn main() { assert_eq!(Maybe::Just(1).try_unwrap_just(), Ok(1)); // Unlike `Unwrap`, it does not panic. assert_eq!( Maybe::<()>::Nothing.try_unwrap_just().map_err(|err| err.input), Err(Maybe::<()>::Nothing), // and the value is returned! ); assert_eq!( Maybe::Just(2).try_unwrap_nothing().map_err(|err| err.input), Err(Maybe::Just(2)), ); assert_eq!( Maybe::<()>::Nothing.try_unwrap_just().map_err(|err| err.to_string()), Err("Attempt to call `Maybe::try_unwrap_just()` on a `Maybe::Nothing` value".into()), ); assert_eq!((&Maybe::Just(42)).try_unwrap_just_ref(), Ok(&42)); assert_eq!((&mut Maybe::Just(42)).try_unwrap_just_mut(), Ok(&mut 42)); } ``` -------------------------------- ### Struct Hashing Example Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/hash.md Demonstrates deriving Hash for a generic struct. This generates code equivalent to manually implementing the Hash trait by hashing all available fields. ```rust # use std::marker::PhantomData; # use derive_more::Hash; # trait Trait { type Assoc; } impl Trait for T { type Assoc = u8; } #[derive(Debug, Hash)] struct Foo { a: A, b: PhantomData, c: C::Assoc, } #[derive(Debug)] struct NoHash; ``` ```rust # use std::marker::PhantomData; # use derive_more::core::hash::{Hash, Hasher}; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # # struct Foo { # a: A, # b: PhantomData, # c: C::Assoc, # } # impl Hash for Foo where A: Hash, PhantomData: Hash, // `B: Hash` is generated by `std` instead C::Assoc: Hash, // `C: Hash` is generated by `std` instead { fn hash(&self, state: &mut H) { match self { Self { a: self_0, b: self_1, c: self_2 } => { self_0.hash(state); self_1.hash(state); self_2.hash(state); } } } } ``` -------------------------------- ### Example Usage of IsVariant Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/is_variant.md Demonstrates how to use `#[derive(IsVariant)]` on an enum and how to call the generated `is_` methods. Ensure the `derive_more::IsVariant` is imported. ```rust use derive_more::IsVariant; #[derive(IsVariant)] enum Maybe { Just(T), Nothing } assert!(Maybe::<()>::Nothing.is_nothing()); assert!(!Maybe::<()>::Nothing.is_just()); ``` -------------------------------- ### Enum Hashing Example Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/hash.md Demonstrates deriving Hash for a generic enum. The discriminant is hashed first, followed by the fields of the active variant. ```rust # use std::marker::PhantomData; # use derive_more::Hash; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # #[derive(Debug, Hash)] enum Foo { A(A), B { b: PhantomData }, C(C::Assoc), } # # #[derive(Debug)] # struct NoHash; ``` ```rust # use std::marker::PhantomData; # use derive_more::core::hash::{Hash, Hasher}; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # # enum Foo { # A(A), # B { b: PhantomData }, # C(C::Assoc), # } # impl Hash for Foo where A: Hash, PhantomData: Hash, // `B: Hash` is generated by `std` instead C::Assoc: Hash, // `C: Hash` is generated by `std` instead { fn hash(&self, state: &mut H) { std::mem::discriminant(self).hash(state); match self { Self::A(self_0) => { self_0.hash(state); } Self::B { b: self_0 } => { self_0.hash(state); } Self::C(self_0) => { self_0.hash(state); } } } } ``` -------------------------------- ### Multiple Forwarded Impls with Different Types Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/as_mut.md This example shows how to use multiple forwarded `AsMut` implementations with different concrete types by specifying the target type in the attribute. ```rust # use derive_more::AsMut; #[derive(AsMut)] struct Types { #[as_mut(str)] str: String, #[as_mut([u8])] vec: Vec, } let mut item = Types { str: "test".to_owned(), vec: vec![0u8], }; let _: &mut str = item.as_mut(); let _: &mut [u8] = item.as_mut(); ``` -------------------------------- ### Forwarding with Other Fields Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/as_mut.md This example demonstrates an error when `#[as_mut(forward)]` is used on one field, and another field is also annotated with `#[as_mut]`. Only one field can be forwarded. ```rust # use derive_more::AsMut; // Error! Conflicting implementations of `AsMut` // note: upstream crates may add a new impl of trait `AsMut` // for type `String` in future versions #[derive(AsMut)] struct ForwardWithOther { #[as_mut(forward)] str: String, #[as_mut] number: i32, } ``` -------------------------------- ### Example Usage of IndexMut Derivation Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/index_mut.md Demonstrates deriving and using IndexMut for both tuple structs and regular structs. Ensure that the Index trait is also derived for the same field. ```rust # use derive_more::{Index, IndexMut}; # #[derive(Index, IndexMut)] struct MyVec(Vec); #[derive(Index, IndexMut)] struct Numbers { #[index] #[index_mut] numbers: Vec, useless: bool, } let mut myvec = MyVec(vec![5, 8]); myvec[0] = 50; assert_eq!(50, myvec[0]); let mut numbers = Numbers{numbers: vec![100, 200], useless: false}; numbers[1] = 400; assert_eq!(400, numbers[1]); ``` -------------------------------- ### Struct Equality with derive_more Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/eq.md Deriving Eq/PartialEq for structs compares all available fields for equality. This example demonstrates its usage with a generic struct. ```rust # use std::marker::PhantomData; # use derive_more::{Eq, PartialEq}; # trait Trait { type Assoc; } impl Trait for T { type Assoc = u8; } #[derive(Debug, Eq, PartialEq)] struct Foo { a: A, b: PhantomData, c: C::Assoc, } #[derive(Debug)] struct NoEq; assert_eq!(Foo::<_, NoEq, NoEq> { a: 3, b: PhantomData, c: 0 }, Foo { a: 3, b: PhantomData, c: 0 }); assert_ne!(Foo::<_, NoEq, NoEq> { a: 3, b: PhantomData, c: 0 }, Foo { a: 0, b: PhantomData, c: 3 }); ``` ```rust # use std::marker::PhantomData; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # # struct Foo { # a: A, # b: PhantomData, # c: C::Assoc, # } # impl PartialEq for Foo where A: PartialEq, PhantomData: PartialEq, // `B: PartialEq` is generated by `std` instead C::Assoc: PartialEq, // `C: PartialEq` is generated by `std` instead { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self { a: self_0, b: self_1, c: self_2 }, Self { a: other_0, b: other_1, c: other_2 }) => { self_0 == other_0 && self_1 == other_1 && self_2 == other_2 } } } fn ne(&self, other: &Self) -> bool { match (self, other) { (Self { a: self_0, b: self_1, c: self_2 }, Self { a: other_0, b: other_1, c: other_2 }) => { self_0 != other_0 || self_1 != other_1 || self_2 != other_2 } } } } impl Eq for Foo where Self: PartialEq, A: Eq, PhantomData: Eq, // `B: Eq` is generated by `std` instead C::Assoc: Eq, // `C: Eq` is generated by `std` instead {} ``` -------------------------------- ### Assertions for Error Source Checks Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md Provides example assertions to verify the behavior of error source retrieval for various custom error types. ```rust assert!(Simple.source().is_none()); assert!(request_ref::(&Simple).is_none()); assert!(WithSource::default().source().is_some()); assert!(WithOptionalSource { source: Some(Simple) }.source().is_some()); assert!(WithExplicitSource::default().source().is_some()); assert!(WithExplicitOptionalSource { explicit_source: Some(Simple) }.source().is_some()); assert!(WithExplicitRenamedOptionalSource { explicit_source: Some(Simple) }.source().is_some()); assert!(Tuple::default().source().is_some()); assert!(WithoutSource::default().source().is_none()); let with_source_and_backtrace = WithSourceAndBacktrace { source: Simple, backtrace: Backtrace::capture(), }; assert!(with_source_and_backtrace.source().is_some()); assert!(request_ref::(&with_source_and_backtrace).is_some()); assert!(CompoundError::Simple.source().is_none()); assert!(CompoundError::from(Simple).source().is_some()); assert!(CompoundError::from(Some(Simple)).source().is_some()); assert!(CompoundError::from(WithSource::default()).source().is_some()); assert!(CompoundError::from(Some(WithSource::default())).source().is_some()); assert!(CompoundError::from(WithExplicitSource::default()).source().is_some()); assert!(CompoundError::from(Some(WithExplicitSource::default())).source().is_some()); assert!(CompoundError::from(Some(WithExplicitRenamedOptionalSource { explicit_source: Some(Simple) })).source().is_some()); assert!(CompoundError::from(Tuple::default()).source().is_none()); ``` -------------------------------- ### Example Usage of #[derive(Deref)] Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/deref.md Demonstrates various ways to use `#[derive(Deref)]` with structs and enums, including single fields, boxed types, and vectors. Shows assertions to verify dereferencing behavior. ```rust # use derive_more::Deref; # #[derive(Deref)] struct Num { num: i32, } #[derive(Deref)] enum Enum { V1(i32), V2 { num: i32 }, } #[derive(Deref)] #[deref(forward)] struct MyBoxedInt(Box); #[derive(Deref)] #[deref(forward)] enum MyBoxedIntEnum { V1(Box), V2 { num: Box }, } // You can specify the field you want to derive `Deref` for. #[derive(Deref)] struct CoolVec { cool: bool, #[deref] vec: Vec, } #[derive(Deref)] enum CoolVecEnum { V1(Vec), V2 { cool: bool, #[deref] vec: Vec }, } let num = Num{num: 123}; let boxed = MyBoxedInt(Box::new(123)); let cool_vec = CoolVec{cool: true, vec: vec![123]}; assert_eq!(123, *num); assert_eq!(123, *boxed); assert_eq!(vec![123], *cool_vec); let num_v2 = Enum::V2{num: 123}; let boxed_v1 = MyBoxedIntEnum::V1(Box::new(123)); let cool_vec_v2 = CoolVecEnum::V2{cool: true, vec: vec![123]}; assert_eq!(123, *num_v2); assert_eq!(123, *boxed_v1); assert_eq!(vec![123], *cool_vec_v2); ``` -------------------------------- ### Conflicting AsMut Implementations Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/as_mut.md This example shows an error when multiple fields are annotated with `#[as_mut]` and would result in conflicting implementations of `AsMut`. ```rust # use derive_more::AsMut; // Error! Conflicting implementations of AsMut #[derive(AsMut)] struct MyWrapper { #[as_mut] str1: String, #[as_mut] str2: String, } ``` -------------------------------- ### Derive TryInto for Enum with Unit Variant Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/try_into.md This example shows how `#[derive(TryInto)]` handles enums containing unit variants. Note that `TryInto` is not generated for unit variants as they do not contain data to convert. ```rust use derive_more::TryInto; #[derive(TryInto)] enum EnumWithUnit { SmallInt(i32), Unit, } ``` -------------------------------- ### Struct with Custom Display Format Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/display.md Example of deriving `Display` for a struct with a custom format string. The format string uses field names and supports pointer formatting (`:p`). ```rust use derive_more::with_trait::Display; #[derive(Display)] #[display("{field:p} {:p}", *field)] struct RefInt<'a> { field: &'a i32, } let a = &123; assert_eq!(format!("{}", RefInt{field: &a}), format!("{a:p} {:p}", a)); ``` -------------------------------- ### Transparent Display Derivation Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/display.md Example of deriving `Display` for a simple tuple struct where the format is not explicitly specified, leading to transparent delegation to the inner type's `Display` implementation. ```rust use derive_more::Display; #[derive(Display)] struct MyInt(i32); assert_eq!(format!("{:03}", MyInt(7)), "007"); ``` -------------------------------- ### Example Usage of DerefMut Derives Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/deref_mut.md Demonstrates the usage of `#[derive(Deref, DerefMut)]` on structs and enums, including cases with nested types like `Box` and `Vec`. Shows how to dereference and mutate the wrapped values. ```rust use derive_more::{Deref, DerefMut}; #[derive(Deref, DerefMut)] struct Num { num: i32, } #[derive(Deref, DerefMut)] enum Enum { V1(i32), V2 { num: i32 }, } #[derive(Deref, DerefMut)] #[deref(forward)] #[deref_mut(forward)] struct MyBoxedInt(Box); #[derive(Deref, DerefMut)] #[deref(forward)] #[deref_mut(forward)] enum MyBoxedIntEnum { V1(Box), V2 { num: Box }, } // You can specify the field you want to derive DerefMut for #[derive(Deref, DerefMut)] struct CoolVec { cool: bool, #[deref] #[deref_mut] vec: Vec, } #[derive(Deref, DerefMut)] enum CoolVecEnum { V1(Vec), V2 { cool: bool, #[deref] #[deref_mut] vec: Vec, }, } let mut num = Num{num: 123}; let mut boxed = MyBoxedInt(Box::new(123)); let mut cool_vec = CoolVec{cool: true, vec: vec![123]}; *num += 123; assert_eq!(246, *num); *boxed += 1000; assert_eq!(1123, *boxed); cool_vec.push(456); assert_eq!(vec![123, 456], *cool_vec); ``` -------------------------------- ### Deriving Traits for Custom Types Source: https://github.com/jeltef/derive_more/blob/master/README.md This example demonstrates how to use derive_more to automatically implement traits such as Add, Display, From, and Into for custom structs and enums. It shows usage with a newtype pattern struct, a struct with fields, and an enum with different variants. ```rust use derive_more::{Add, Display, From, Into}; #[derive(PartialEq, From, Add)] struct MyInt(i32); #[derive(PartialEq, From, Into)] struct Point2D { x: i32, y: i32, } #[derive(PartialEq, From, Add, Display)] enum MyEnum { #[display("int: {_0}")] Int(i32), Uint(u32), #[display("nothing")] Nothing, } assert!(MyInt(11) == MyInt(5) + 6.into()); assert!((5, 6) == Point2D { x: 5, y: 6 }.into()); assert!(MyEnum::Int(15) == (MyEnum::Int(8) + 7.into()).unwrap()); assert!(MyEnum::Int(15).to_string() == "int: 15"); assert!(MyEnum::Uint(42).to_string() == "42"); assert!(MyEnum::Nothing.to_string() == "nothing"); ``` -------------------------------- ### Basic Error Structs with derive_more Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md Define simple error types that implement `std::error::Error` and `std::fmt::Display` using `derive_more`. These examples show basic structs and structs with a source error. ```rust #[derive(Default, Debug, Display, Error)] struct Simple; #[derive(Default, Debug, Display, Error)] struct WithSource { source: Simple, } ``` ```rust #[derive(Default, Debug, Display, Error)] #[display("WithOptionalSource")] struct WithOptionalSource { source: Option, } ``` ```rust #[derive(Default, Debug, Display, Error)] struct WithExplicitSource { #[error(source)] explicit_source: Simple, } ``` ```rust #[derive(Default, Debug, Display, Error)] #[display("WithExplicitOptionalSource")] struct WithExplicitOptionalSource { #[error(source)] explicit_source: Option, } ``` ```rust #[derive(Default, Debug, Display, Error)] #[display("WithExplicitOptionalSource")] struct WithExplicitRenamedOptionalSource { #[error(source(optional))] explicit_source: RenamedOption, } ``` -------------------------------- ### Conflicting AsRef Implementations Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/as_ref.md When deriving AsRef, only one field can be marked with `#[as_ref]`. This example shows a compile-time error when multiple fields are annotated. ```rust # use derive_more::AsRef; // Error! Conflicting implementations of AsRef #[derive(AsRef)] struct MyWrapper { #[as_ref] str1: String, #[as_ref] str2: String, } ``` -------------------------------- ### No-std Environment Configuration Source: https://github.com/jeltef/derive_more/blob/master/README.md For no_std environments, disable default features and optionally combine with the 'full' feature for all derives. ```toml [dependencies] # If you run in a `no_std` environment you should disable the default features, # because the only default feature is the "std" feature. # NOTE: You can combine this with "full" feature to get support for all the # possible derives in a `no_std` environment. derive_more = { version = "2", default-features = false } ``` -------------------------------- ### Manual TryFrom Implementation for Enum Variants Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/try_into.md Demonstrates manual implementation of TryFrom for specific enum variants to target types like i32 and unit. ```rust impl TryFrom for (i32) { type Error = derive_more::TryIntoError; fn try_from(value: EnumWithUnit) -> Result> { match value { EnumWithUnit::SmallInt(__0) => Ok(__0), _ => Err(derive_more::TryIntoError::new(value, "SmallInt", "i32")), } } } impl TryFrom for () { type Error = derive_more::TryIntoError; fn try_from(value: EnumWithUnit) -> Result> { match value { EnumWithUnit::Unit => Ok(()), _ => Err(derive_more::TryIntoError::new(value, "Unit", "()")), } } } ``` -------------------------------- ### Generated AddAssign Implementation for Structs Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/add_assign.md This shows the equivalent manual implementation of `AddAssign` for structs, demonstrating field-wise in-place addition. ```rust use std::ops::AddAssign; struct MyInts(i32, i32); struct Point2D { x: i32, y: i32, } impl AddAssign for MyInts { fn add_assign(&mut self, rhs: Self) { match (self, rhs) { (Self(self_0, self_1), Self(rhs_0, rhs_1)) => { AddAssign::add_assign(self_0, rhs_0); AddAssign::add_assign(self_1, rhs_1); } } } } impl AddAssign for Point2D { fn add_assign(&mut self, rhs: Self) { match (self, rhs) { (Self { x: self_0, y: self_1 }, Self { x: rhs_0, y: rhs_1 }) => { AddAssign::add_assign(self_0, rhs_0); AddAssign::add_assign(self_1, rhs_1); } } } } ``` -------------------------------- ### Transparent Formatting with Display Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/display.md Demonstrates how the Display derive macro transparently uses underlying formatting traits like Octal and Binary. Additional formatting parameters may or may not have an effect depending on the underlying trait's support. ```rust #[derive(Display)] #[display("{_0:o}")] // the same as calling `Octal::fmt()` struct MyOctalInt(i32); // so, additional formatting parameters do work transparently assert_eq!(format!({"%03"}, MyOctalInt(9)), "011"); ``` ```rust #[derive(Display)] #[display("{_0:02b}")] // cannot be trivially substituted with `Binary::fmt()`, struct MyBinaryInt(i32); // because of specified formatting parameters // so, additional formatting parameters have no effect assert_eq!(format!({"%07"}, MyBinaryInt(2)), "10"); ``` -------------------------------- ### Compile-fail: Renamed Option Type Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md This example demonstrates a compile-fail scenario where a renamed Option type is not automatically recognized as an Option for deriving source(). ```rust # use derive_more::{Display, Error}; # #[derive(Debug, Display, Error)] # struct Simple; #[derive(Debug, Display, Error)] #[display("Oops!")] struct Generic(RenamedOption); // not recognized as `Option` type RenamedOption = Option; ``` -------------------------------- ### Enum Equality with derive_more Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/eq.md Deriving Eq/PartialEq for enums first checks if variants match, then compares fields. This example shows usage with a generic enum. ```rust # use std::marker::PhantomData; # use derive_more::{Eq, PartialEq}; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # #[derive(Debug, Eq, PartialEq)] enum Foo { A(A), B { b: PhantomData }, C(C::Assoc), } # # #[derive(Debug)] # struct NoEq; assert_eq!(Foo::<_, NoEq, NoEq>::A(3), Foo::A(3)); assert_ne!(Foo::<_, NoEq, NoEq>::A(3), Foo::A(0)); assert_eq!(Foo::::B { b: PhantomData }, Foo::B { b: PhantomData }); assert_eq!(Foo::::C(3), Foo::C(3)); assert_ne!(Foo::::C(3), Foo::C(0)); ``` ```rust # use std::marker::PhantomData; # # trait Trait { # type Assoc; # } # impl Trait for T { # type Assoc = u8; # } # # enum Foo { # A(A), # B { b: PhantomData }, # C(C::Assoc), # } # impl PartialEq for Foo where A: PartialEq, PhantomData: PartialEq, // `B: PartialEq` is generated by `std` instead C::Assoc: PartialEq, // `C: PartialEq` is generated by `std` instead { fn eq(&self, other: &Self) -> bool { std::mem::discriminant(self) == std::mem::discriminant(other) && match (self, other) { (Self::A(self_0), Self::A(other_0)) => { self_0 == other_0 } (Self::B { b: self_0 }, Self::B { b: other_0 }) => { self_0 == other_0 } (Self::C(self_0), Self::C(other_0)) => { self_0 == other_0 } _ => unsafe { std::hint::unreachable_unchecked() } } } fn ne(&self, other: &Self) -> bool { std::mem::discriminant(self) != std::mem::discriminant(other) || match (self, other) { (Self::A(self_0), Self::A(other_0)) => { self_0 != other_0 } (Self::B { b: self_0 }, Self::B { b: other_0 }) => { self_0 != other_0 } (Self::C(self_0), Self::C(other_0)) => { self_0 != other_0 } _ => unsafe { std::hint::unreachable_unchecked() } } } } impl Eq for Foo where Self: PartialEq, A: Eq, PhantomData: Eq, // `B: Eq` is generated by `std` instead C::Assoc: Eq, // `C: Eq` is generated by `std` instead {} ``` -------------------------------- ### Enable All Derives with 'full' Feature Source: https://github.com/jeltef/derive_more/blob/master/README.md Use the 'full' feature in Cargo.toml to enable all possible derives if compilation time is not a primary concern. ```toml [dependencies] # If you don't care much about compilation times and simply want to have # support for all the possible derives, you can use the "full" feature. derive_more = { version = "2", features = ["full"] } ``` -------------------------------- ### Deriving IntoIterator for a Struct Field Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/into_iterator.md Use `#[into_iterator]` to specify which field to derive `IntoIterator` for. This example shows deriving for owned, referenced, and mutable referenced types. ```rust use derive_more::IntoIterator; #[derive(IntoIterator)] struct MyVec(Vec); // You can specify the field you want to derive `IntoIterator` for #[derive(IntoIterator)] struct Numbers { #[into_iterator(owned, ref, ref_mut)] numbers: Vec, useless: bool, } assert_eq!(Some(5), MyVec(vec![5, 8]).into_iter().next()); let mut nums = Numbers { numbers: vec![100, 200], useless: false }; assert_eq!(Some(&100), (&nums).into_iter().next()); assert_eq!(Some(&mut 100), (&mut nums).into_iter().next()); assert_eq!(Some(100), nums.into_iter().next()); ``` -------------------------------- ### Compile-fail: Custom Option Type Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md This example demonstrates a compile-fail scenario where a custom type named Option is not recognized as std::option::Option for deriving source(). ```rust # use derive_more::{Display, Error}; # #[derive(Debug, Display, Error)] # struct Simple; #[derive(Debug, Display, Error)] #[display("No way!")] struct Generic(Option); // cannot use `?` syntax struct Option(T); ``` -------------------------------- ### Custom Debug Formatting with derive_more Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/debug.md Illustrates various ways to customize debug output using `#[derive(Debug)]` and the `#[debug(...)]` attribute. This includes custom formats for integers, structs, enums, and handling skipped fields. ```rust use std::path::PathBuf; use derive_more::Debug; #[derive(Debug)] struct MyInt(i32); #[derive(Debug)] struct MyIntHex(#[debug("{_0:x}")] i32); #[derive(Debug)] #[debug("{_0} = {_1}")] struct StructFormat(&'static str, u8); #[derive(Debug)] enum E { Skipped { x: u32, #[debug(skip)] // or #[debug(ignore)] y: u32, }, Binary { #[debug("{i:b}")] i: i8, }, Path(#[debug("{}.display()", _0)] PathBuf), #[debug("{_0}")] EnumFormat(bool) } assert_eq!(format!("{:?}", MyInt(-2)), "MyInt(-2)"); assert_eq!(format!("{:?}", MyIntHex(-255)), "MyIntHex(ffffff01)"); assert_eq!(format!("{:?}", StructFormat("answer", 42)), "answer = 42"); assert_eq!(format!("{:?}", E::Skipped { x: 10, y: 20 }), "Skipped { x: 10, .. }"); assert_eq!(format!("{:?}", E::Binary { i: -2 }), "Binary { i: 11111110 }"); assert_eq!(format!("{:?}", E::Path("abc".into())), "Path(abc)"); assert_eq!(format!("{:?}", E::EnumFormat(true)), "true"); ``` -------------------------------- ### Customizing Display with Methods Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/display.md Implement custom display logic for structs by defining a method and referencing it within the `#[display(...)]` attribute. This allows for dynamic formatting based on the struct's state. ```rust #[derive(Display)] #[display("{}", self.sign())] struct PositiveOrNegative { x: i32, } impl PositiveOrNegative { fn sign(&self) -> &str { if self.x >= 0 { "Positive" } else { "Negative" } } } assert_eq!(PositiveOrNegative { x: 1 }.to_string(), "Positive"); assert_eq!(PositiveOrNegative { x: -1 }.to_string(), "Negative"); ``` -------------------------------- ### Tuple Structs and Errors without Sources Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md Illustrates defining error types using tuple structs and explicitly marking fields that should not be treated as error sources. ```rust #[derive(Default, Debug, Display, Error)] struct Tuple(Simple); #[derive(Default, Debug, Display, Error)] struct WithoutSource(#[error(not(source))] i32); ``` -------------------------------- ### Enum Renaming with from_str Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/from_str.md Demonstrates how to use `#[from_str(rename_all = "...")]` to control the string representation of enum variants. The `kebab-case` override for `VariantTwo` shows how to apply renaming rules at the variant level. ```rust #[derive(FromStr, Debug, Eq, PartialEq)] #[from_str(rename_all = "lowercase")] enum Enum { VariantOne, #[from_str(rename_all = "kebab-case")] // overrides the top-level one VariantTwo } assert_eq!("variantone".parse::().unwrap(), Enum::VariantOne); assert_eq!("variant-two".parse::().unwrap(), Enum::VariantTwo); ``` -------------------------------- ### Wrapping Enum Format with Display Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/display.md Demonstrates how to use a shared top-level `#[display]` attribute on an enum to act as a wrapping format. The `{_variant}` placeholder is used to insert the format string of individual variants. ```rust # use derive_more::Display; # #[derive(Display)] #[display("Variant: {_variant} & {}", _variant)] enum Enum { #[display("A {}")] A(i32), B { field: i32 }, #[display("c")] C, } assert_eq!(Enum::A(1).to_string(), "Variant: A 1 & A 1"); assert_eq!(Enum::B { field: 2 }.to_string(), "Variant: 2 & 2"); assert_eq!(Enum::C.to_string(), "Variant: c & c"); ``` -------------------------------- ### Multiple Forwarded AsRef Implementations Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/as_ref.md Multiple fields can be forwarded using `#[as_ref]` with specific types, allowing different reference types to be derived from different fields. ```rust # use derive_more::AsRef; #[derive(AsRef)] struct Types { #[as_ref(str)] str: String, #[as_ref([u8])] vec: Vec, } let item = Types { str: "test".to_owned(), vec: vec![0u8], }; let _: &str = item.as_ref(); let _: &[u8] = item.as_ref(); ``` -------------------------------- ### Custom Debug Formatting with Pointer Type Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/debug.md Use `#[debug]` with format specifiers like `:p` for pointer formatting. Dereference fields once when not using `{field:p}` to get the field's address. ```rust use derive_more::Debug; #[derive(Debug)] #[debug("{field:p} {:p}", *field)] struct RefInt<'a> { field: &'a i32, } let a = &123; assert_eq!(format!("{:?}", RefInt { field: &a }), format!("{:p} {:p}", a)); ``` -------------------------------- ### Enable Specific Derives Source: https://github.com/jeltef/derive_more/blob/master/README.md Specify individual derive features in Cargo.toml to reduce compilation times. Consult the crate's Cargo.toml for a complete list of features. ```toml [dependencies] # You can specify the types of derives that you need for less time spent # compiling. For the full list of features see this crate its `Cargo.toml`. derive_more = { version = "2", features = ["from", "add", "into_iterator"] } ``` -------------------------------- ### Deriving Error with Source and Backtrace Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md This example demonstrates deriving Error for a struct with named fields, where one field is designated as the source and another as the backtrace. It requires nightly Rust and enabling the error_generic_member_access feature. ```rust #![cfg_attr(nightly, feature(error_generic_member_access))] # // Nightly requires enabling this feature: # // #![feature(error_generic_member_access)] # #[cfg(not(nightly))] fn main() {} # #[cfg(nightly)] fn main() { # use core::error::{request_ref, request_value, Error as __}; # use std::backtrace::Backtrace; # # use derive_more::{Display, Error, From}; # # type RenamedOption = Option; ``` -------------------------------- ### Rust: Generated Eq/PartialEq implementation for Bar Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/eq.md This is the generated code equivalent to the `Bar` struct with the `#[partial_eq(skip)]` attribute, showing that all fields are ignored, resulting in a trivial `PartialEq` implementation where all instances are considered equal. ```rust # struct NoEq; # # struct Bar(i32, NoEq); # impl PartialEq for Bar { fn eq(&self, __other: &Self) -> bool { true } } impl Eq for Bar {} ``` -------------------------------- ### Renamed Option Field with #[error(source(optional))] Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md This example shows how to handle a renamed Option type for the source field by using the #[error(source(optional))] attribute. This is necessary when std::option::Option is not directly used or is renamed. ```rust # use derive_more::{Display, Error}; # #[derive(Debug, Display, Error)] # struct Simple; #[derive(Debug, Display, Error)] #[display("Oops!")] struct Generic(#[error(source(optional))] RenamedOption); type RenamedOption = Option; ``` -------------------------------- ### Rust: Define and Use Custom Hash Function Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/hash.md Demonstrates how to define a custom hash function for an i32 field and apply it using the `#[hash(with(function))]` attribute. The custom function `hash_abs` takes a reference to the field value and a mutable hasher state. ```rust # use derive_more::Hash; mod my_hash { use core::hash::Hasher; pub fn hash_abs(value: &i32, state: &mut H) { state.write_i32(value.abs()); } } #[derive(Hash)] struct Foo { #[hash(with(my_hash::hash_abs))] value: i32, } ``` ```rust # use derive_more::core::hash::{Hash, Hasher}; # mod my_hash { # use derive_more::core::hash::Hasher; # # pub fn hash_abs(value: &i32, state: &mut H) { # state.write_i32(value.abs()); # } # } # # struct Foo { # value: i32, # } # impl Hash for Foo { fn hash(&self, state: &mut H) { match self { Self { value: self_0 } => { my_hash::hash_abs(self_0, state); } } } } ``` -------------------------------- ### Importing only derive macros Source: https://github.com/jeltef/derive_more/blob/master/README.md By default, importing from the crate's root or the `derive` module brings only the derive macros into scope, not the traits themselves. This is the standard way to use the derive macros. ```rust use derive_more::Display; // imports macro only use derive_more::derive::*; // imports all macros only ``` -------------------------------- ### Error with Backtrace Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/error.md Demonstrates how to include a backtrace with an error type using `derive_more::Error` and `Backtrace`. ```rust #[derive(Debug, Display, Error)] #[display("An error with a backtrace")] struct WithSourceAndBacktrace { source: Simple, backtrace: Backtrace, } ``` -------------------------------- ### Sum Derivation for Structs Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/sum.md Shows the basic structure for deriving Sum on a struct. The implementation relies on the Add trait. ```rust # use derive_more::{Add, Sum}; # #[derive(Add, Sum)] struct MyInts(i32, i64); ``` -------------------------------- ### Derive Into for References (Owned, Ref, RefMut) Source: https://github.com/jeltef/derive_more/blob/master/impl/doc/into.md Use `#[into(owned, ref(...))]` and `#[into(ref_mut)]` to derive conversions into owned, borrowed, and mutable borrowed types. ```rust # use derive_more::Into; # #[derive(Debug, Into, PartialEq)] #[into(owned, ref(i32), ref_mut)] struct Int(i32); assert_eq!(2, Int(2).into()); assert_eq!(&2, <&i32>::from(&Int(2))); assert_eq!(&mut 2, <&mut i32>::from(&mut Int(2))); ``` -------------------------------- ### Import Derives in Rust File Source: https://github.com/jeltef/derive_more/blob/master/README.md Import the specific derives you intend to use at the top of your Rust source file. ```rust // use the derives that you want in the file use derive_more::{Add, Display, From}; ```