How do you derive Default for a Rust enum such as LogLevel, and which rules does the #[default] attribute enforce?
answer
- enums have no obvious winner
- an attribute on one variant
- stable since 1.62
- unit, single, exhaustive
basics
~10 sMark exactly one unit variant with #[default] and derive Default; default() returns that variant. Stable since Rust 1.62, it rejects a missing mark (E0665), two marks, a variant carrying data, or a #[non_exhaustive] variant.
solid answer
~30 sSince Rust 1.62 you write `#[derive(Default)]` on the enum and put `#[default]` on one variant, say `Warn`; `LogLevel::default()` then returns `LogLevel::Warn`. rustc enforces four rules: some variant must be marked (otherwise E0665), only one may be marked ("multiple declared defaults"), it must be a unit variant ("may only be used on unit enum variants"), and it must not be `#[non_exhaustive]`. For a default that carries data, such as `Verbose(1)`, you write `impl Default` by hand. Since 1.66 the derive on a generic enum adds no `T: Default` bound, because the unit default variant holds no `T`.
code
rust · 20 lines#[derive(Debug, Default, Clone, Copy, PartialEq)]
enum LogLevel {
Error,
#[default]
Warn,
Info,
Debug,
}
#[derive(Debug, Default)]
struct ServerConfig {
port: u16,
log_level: LogLevel, // the derived impl calls LogLevel::default()
}
fn main() {
let cfg = ServerConfig::default();
assert_eq!(cfg.log_level, LogLevel::Warn);
println!("{cfg:?}");
}go deeper
Recall the syntax: #[derive(Default)] on the enum and #[default] on the chosen variant, and that without the mark the derive does not compile.
Explain the four rules rustc enforces, one marked variant, unit only, not non_exhaustive, and E0665 when none is marked, plus the hand-written impl for a variant with data.
Know the release history: 1.62 stabilised the attribute and 1.66 dropped the needless T: Default bound on generic enums, which matters when a crate supports an older minimum Rust version.
Treat the default variant as API: moving #[default] changes behaviour for every caller using Default::default(), so it deserves the same review and release notes as a renamed function.
## Why an enum needs a marker A struct has an obvious default: the default of every field. An enum has several variants and no obvious winner, so `#[derive(Default)]` cannot guess. Since **Rust 1.62** you choose the variant by putting the **`#[default]`** attribute on it. The derive then generates `impl Default for LogLevel` whose `default()` returns that variant. Before 1.62 the standard way was a hand-written `impl Default`, which is still what you see in older crates. ```rust #[derive(Debug, Default, Clone, Copy, PartialEq)] enum LogLevel { Error, #[default] Warn, Info, Debug, } ``` A struct that holds a `LogLevel` can now derive `Default` too, because its derived `default()` calls `LogLevel::default()` for that field. ## The rules rustc enforces rustc 1.99 checks four things when it expands the derive on an enum: 1. **Exactly one variant must be marked.** With none, the build fails with **E0665**, "`#[derive(Default)]` on enum with no `#[default]`", and rustc suggests a unit variant to mark. 2. **Only one.** Two marks produce "multiple declared defaults" with the note "only one variant can be default". There is no "first one wins". 3. **Unit variants only.** `#[default]` on `Verbose(u8)` or on a struct-like variant produces "the `#[default]` attribute may only be used on unit enum variants". The derive does not fill a payload with its own defaults. 4. **Not `#[non_exhaustive]`.** A marked variant that is also `#[non_exhaustive]` produces "default variant must be exhaustive". The standard library documentation sums up rules 3 and 4 in one line: you cannot use the `#[default]` attribute on non-unit or non-exhaustive variants. | What you write | What rustc 1.99 does | |---|---| | `#[default]` on one unit variant | derives `Default` returning that variant | | no `#[default]` anywhere | E0665 | | `#[default]` on two variants | error: multiple declared defaults | | `#[default]` on `Verbose(u8)` | error: may only be used on unit enum variants | | `#[default]` with `#[non_exhaustive]` on the variant | error: default variant must be exhaustive | | `#[default]` on a struct field | error: may only be used on unit enum variants | ## Generic enums do not pick up extra bounds For a generic struct the derive bounds every type parameter with `Default`. For an enum with a `#[default]` unit variant that bound is useless, because the default variant holds no `T`, and since **Rust 1.66** the derive leaves it out: ```rust #[derive(Debug, Default)] enum Slot<T> { #[default] Empty, Full(T), } struct Conn; // no Default impl let s: Slot<Conn> = Slot::default(); // compiles: Slot::Empty ``` Before 1.66 the derive added `T: Default` here, so a call like this one with a non-`Default` `T` did not compile; the release notes list the fix as "`#[derive(Default)]` on a generic `#[default]` enum adding unnecessary `Default` bounds". ## Variants with data need a hand-written impl When the sensible default carries data, for example a verbose level with a verbosity of 1, write the impl yourself. The E0665 page in the error-code index gives the same advice for a default variant with a payload: ```rust #[derive(Debug)] enum LogLevel { Error, Warn, Verbose(u8), } impl Default for LogLevel { fn default() -> Self { LogLevel::Verbose(1) } } ``` A hand-written impl is also the route when the default must depend on something else, such as a build-time `cfg!` check. ## Using the derived default Once the enum implements `Default`, everything in std that asks for `T: Default` accepts it: - A struct with a `LogLevel` field can derive `Default`, and its derived `default()` sets the field to `LogLevel::Warn`. - `ServerConfig { port: 9000, ..Default::default() }` leaves the log level at the marked variant. - `Option::<LogLevel>::unwrap_or_default()` returns `Warn` for `None`. - `std::mem::take(&mut cfg.log_level)` moves the current level out and leaves `Warn` behind. The derived impl is an ordinary `impl Default`, so none of these callers can tell it from a hand-written one. ## What interviewers listen for - That `#[derive(Default)]` on an enum needs `#[default]`, and that declaration order picks nothing. - The four restrictions, with E0665 for the missing mark. - That the feature arrived in 1.62, so a codebase with an older minimum supported Rust version still writes the impl by hand. - That the derived default variant is part of the API: changing which variant carries `#[default]` silently changes every caller that used `Default::default()` or `..Default::default()`.
- Does #[derive(Default)] on enum Slot<T> { #[default] Empty, Full(T) } require T: Default?Not on current Rust. The default variant is a unit variant and holds no `T`, and since Rust 1.66 the derive adds no `Default` bound for a generic enum, so `Slot::<Conn>::default()` compiles even when `Conn` has no `Default`. Before 1.66 the derive added the bound, so that call did not compile.
- How do you make a variant that carries data, such as Verbose(u8), the default?Write `impl Default for LogLevel { fn default() -> Self { LogLevel::Verbose(1) } }`. The derive refuses `#[default]` on a variant with fields ("may only be used on unit enum variants"), and the error-code index's page for E0665 gives the same advice for a default with a payload.
- Deriving Default on an enum picks the first declared variant automatically.
- #[default] can mark a tuple variant and fills its fields with their defaults.
- #[derive(Default)] on enums has worked since Rust 1.0.
- With #[default] on two variants, the first one in declaration order wins.
- A generic enum with a #[default] unit variant needs T: Default to derive Default.
Assumes Rust 1.99; #[default] on enum variants is stable since 1.62, and since 1.66 the derive adds no Default bound for a generic enum.