Crate derive_more
source ·Expand description
derive_more
Rust has lots of builtin traits that are implemented for its basic types, such
as Add
, Not
, From
or Display
.
However, when wrapping these types inside your own structs or enums you lose the
implementations of these traits and are required to recreate them.
This is especially annoying when your own structures are very simple, such as
when using the commonly advised newtype pattern (e.g. MyInt(i32)
).
This library tries to remove these annoyances and the corresponding boilerplate code. It does this by allowing you to derive lots of commonly used traits for both structs and enums.
Example code
By using this library the following code just works:
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");
The derivable traits
Below are all the traits that you can derive using this library. Some trait derivations are so similar that the further documentation will only show a single one of them. You can recognize these by the “-like” suffix in their name. The trait name before that will be the only one that is used throughout the further documentation.
It is important to understand what code gets generated when using one of the derives from this crate. That is why the links below explain what code gets generated for a trait for each group from before.
You can use the cargo-expand
utility to see the exact code that is generated
for your specific type.
This will show you your code with all macros and derives expanded.
NOTE: You still have to derive each trait separately. So #[derive(Mul)]
doesn’t
automatically derive Div
as well. To derive both you should do #[derive(Mul, Div)]
Conversion traits
These are traits that are used to convert automatically between types.
Formatting traits
These traits are used for converting a struct to a string in different ways.
Debug
Display
-like, containsDisplay
,Binary
,Octal
,LowerHex
,UpperHex
,LowerExp
,UpperExp
,Pointer
Error-handling traits
These traits are used to define error-types.
Operators
These are traits that can be used for operator overloading.
Index
Deref
Not
-like, containsNot
andNeg
Add
-like, containsAdd
,Sub
,BitAnd
,BitOr
,BitXor
Mul
-like, containsMul
,Div
,Rem
,Shr
andShl
Sum
-like, containsSum
andProduct
IndexMut
DerefMut
AddAssign
-like, containsAddAssign
,SubAssign
,BitAndAssign
,BitOrAssign
andBitXorAssign
MulAssign
-like, containsMulAssign
,DivAssign
,RemAssign
,ShrAssign
andShlAssign
Static methods
These don’t derive traits, but derive static methods instead.
Constructor
, this derives anew
method that can be used as a constructor. This is very basic if you need more customization for your constructor, check out thederive-new
crate.IsVariant
, for each variantfoo
of an enum type, derives ais_foo
method.Unwrap
, for each variantfoo
of an enum type, derives anunwrap_foo
method.TryUnwrap
, for each variantfoo
of an enum type, derives antry_unwrap_foo
method.
Installation
This library requires Rust 1.65 or higher. To avoid redundant compilation times, by
default no derives are supported. You have to enable each type of derive as a feature
in Cargo.toml
:
[dependencies]
derive_more = "0.99.0"
# 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`.
features = ["from", "add", "iterator"]
# 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.
features = ["full"]
# 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.
default-features = false
And this to the top of your Rust file:
// use the derives that you want in the file
use derive_more::{Add, Display, From};
If you’re still using Rust 2015, add this instead:
extern crate core;
#[macro_use]
extern crate derive_more;
Re-exports
This crate also re-exports all of the standard library traits that it adds
derives for. So both the Display
derive and the Display
trait will be in
scope when you add the following code:
use derive_more::Display;
Modules
Structs
- FromStrError
from_str
Error of parsing an enum value its string representation. - TryIntoError
try_into
Error returned by the derivedTryInto
implementation. - TryUnwrapError
try_unwrap
Error returned by the derivedTryUnwrap
implementation.
Traits
- The addition operator
+
. - The addition assignment operator
+=
. - Used to do a cheap mutable-to-mutable reference conversion.
- Used to do a cheap reference-to-reference conversion.
b
formatting.- The bitwise AND operator
&
. - The bitwise AND assignment operator
&=
. - The bitwise OR operator
|
. - The bitwise OR assignment operator
|=
. - The bitwise XOR operator
^
. - The bitwise XOR assignment operator
^=
. ?
formatting.- Used for immutable dereferencing operations, like
*v
. - Used for mutable dereferencing operations, like in
*v = 1;
. - Format trait for an empty format,
{}
. - The division operator
/
. - The division assignment operator
/=
. Error
is a trait representing the basic expectations for error values, i.e., values of typeE
inResult<T, E>
.- Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
Into
. - Parse a value from a string
- Used for indexing operations (
container[index]
) in immutable contexts. - Used for indexing operations (
container[index]
) in mutable contexts. - A value-to-value conversion that consumes the input value. The opposite of
From
. - Conversion into an
Iterator
. e
formatting.x
formatting.- The multiplication operator
*
. - The multiplication assignment operator
*=
. - The unary negation operator
-
. - The unary logical negation operator
!
. o
formatting.p
formatting.- Trait to represent types that can be created by multiplying elements of an iterator.
- The remainder operator
%
. - The remainder assignment operator
%=
. - The left shift operator
<<
. Note that because this trait is implemented for all integer types with multiple right-hand-side types, Rust’s type checker has special handling for_ << _
, setting the result type for integer operations to the type of the left-hand-side operand. This means that thougha << b
anda.shl(b)
are one and the same from an evaluation standpoint, they are different when it comes to type inference. - The left shift assignment operator
<<=
. - The right shift operator
>>
. Note that because this trait is implemented for all integer types with multiple right-hand-side types, Rust’s type checker has special handling for_ >> _
, setting the result type for integer operations to the type of the left-hand-side operand. This means that thougha >> b
anda.shr(b)
are one and the same from an evaluation standpoint, they are different when it comes to type inference. - The right shift assignment operator
>>=
. - The subtraction operator
-
. - The subtraction assignment operator
-=
. - Trait to represent types that can be created by summing up an iterator.
- An attempted conversion that consumes
self
, which may or may not be expensive. E
formatting.X
formatting.
Derive Macros
- Add
add
What#[derive(Add)]
generates - AddAssign
add_assign
What#[derive(AddAssign)]
generates - AsMut
as_mut
What#[derive(AsMut)]
generates - AsRef
as_ref
What#[derive(AsRef)]
generates - Binary
display
What#[derive(Display)]
generates - BitAnd
add
What#[derive(Add)]
generates - BitAndAssign
add_assign
What#[derive(AddAssign)]
generates - BitOr
add
What#[derive(Add)]
generates - BitOrAssign
add_assign
What#[derive(AddAssign)]
generates - BitXor
add
What#[derive(Add)]
generates - BitXorAssign
add_assign
What#[derive(AddAssign)]
generates - Constructor
constructor
What#[derive(Constructor)]
generates - Debug
debug
What#[derive(Debug)]
generates - Derive macro generating an impl of the trait
Debug
. - Deref
deref
Using#[derive(Deref)]
- DerefMut
deref_mut
What#[derive(DerefMut)]
generates - Display
display
What#[derive(Display)]
generates - Div
mul
What#[derive(Mul)]
generates - DivAssign
mul_assign
What#[derive(MulAssign)]
generates - Error
error
Using#[derive(Error)]
- From
from
What#[derive(From)]
generates - FromStr
from_str
What#[derive(FromStr)]
generates - Index
index
What#[derive(Index)]
generates - IndexMut
index_mut
What#[derive(IndexMut)]
generates - Into
into
What#[derive(Into)]
generates - IntoIterator
into_iterator
Using#[derive(IntoIterator)]
- IsVariant
is_variant
What#[derive(IsVariant)]
generates - LowerExp
display
What#[derive(Display)]
generates - LowerHex
display
What#[derive(Display)]
generates - Mul
mul
What#[derive(Mul)]
generates - MulAssign
mul_assign
What#[derive(MulAssign)]
generates - Neg
not
What#[derive(Not)]
generates - Not
not
What#[derive(Not)]
generates - Octal
display
What#[derive(Display)]
generates - Pointer
display
What#[derive(Display)]
generates - Product
sum
Using#[derive(Sum)]
- Rem
mul
What#[derive(Mul)]
generates - RemAssign
mul_assign
What#[derive(MulAssign)]
generates - Shl
mul
What#[derive(Mul)]
generates - ShlAssign
mul_assign
What#[derive(MulAssign)]
generates - Shr
mul
What#[derive(Mul)]
generates - ShrAssign
mul_assign
What#[derive(MulAssign)]
generates - Sub
add
What#[derive(Add)]
generates - SubAssign
add_assign
What#[derive(AddAssign)]
generates - Sum
sum
Using#[derive(Sum)]
- TryInto
try_into
What#[derive(TryInto)]
generates - TryUnwrap
try_unwrap
What#[derive(TryUnwrap)]
generates - Unwrap
unwrap
What#[derive(Unwrap)]
generates - UpperExp
display
What#[derive(Display)]
generates - UpperHex
display
What#[derive(Display)]
generates