A trait for checking whether a value is the default, with convenient derive support for custom types.
The default value is defined as the value returned by the Default
trait. Therefore, any implementation of IsDefault must ensure that
self == &Self::default() holds true.
Features
| Feature | Default | Description |
|---|---|---|
derive |
yes | Derive trait for a type |
std |
yes | Implements for std-types |
via_default_eq |
no | Generic implementation via Default & PartialEq |
Nightly-only:
| Nightly Feature | Default | Description |
|---|---|---|
nightly |
no | Enable all below nightly features |
ascii_char |
no | Core ascii_char |
f16 |
no | Core f16 |
f128 |
no | Core f128 |
Derive
The IsDefault trait is already implemented for most core and std
types that implement Default. For custom types, you can derive
IsDefault using derive:
# Cargo.toml
[]
= { = "0.1", = ["derive"] }
Structs
A struct can derive IsDefault if all of its fields implement
IsDefault:
#
Enums
When deriving IsDefault for an enum, you must specify which unit
variant should be considered the default. This is done by applying
the #[is_default] or #[default] attribute to the variant:
#
#[default] attribute possible to derive both Default and IsDefault:
#
You can also derive IsDefault for enums that implement both Default
and PartialEq. This approach is more general but may be less
efficient, since a new value must be allocated for comparison:
#
via_default_eq
By default, IsDefault is manually implemented for core and std types.
This approach is fast and has no trait dependencies but requires manual
implementation for custom types.
Alternatively, you can enable a generic implementation of IsDefault
for all types that implement both Default and PartialEq. This is
the simplest option, but it may be less efficient, as it allocates a
new value for comparison:
# Cargo.toml
[]
= { = "0.1.1", = ["via_default_eq"] }
no_std
For no_std builds, add is_default to your Cargo.toml with default
features disabled:
# Cargo.toml
[]
= { = "0.1.1", = false, = ["derive"] }