Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0665: `#[derive(Default)]` on enum with no `#[default]`
What it meansThe Default trait was derived on an enum without specifying the default variant.
What rustc prints
error[E0665]: `#[derive(Default)]` on enum with no `#[default]` --> main.rs:1:10 | 1 | #[derive(Default)] | ^^^^^^^ 2 | / enum Food { 3 | | Sweet, 4 | | Salty, 5 | | } | |_- this enum needs a unit variant marked with `#[default]` | help: make this unit variant default by placing `#[default]` on it | 3 | #[default] Sweet, | ++++++++++ help: make this unit variant default by placing `#[default]` on it | 4 | #[default] Salty, | ++++++++++
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
The Default trait was derived on an enum without specifying the default variant.
Erroneous code example:
#[derive(Default)]
enum Food {
Sweet,
Salty,
}
The Default cannot be derived on an enum for the simple reason that the compiler doesn't know which value to pick by default whereas it can for a struct as long as all its fields implement the Default trait as well.
For the case where the desired default variant has no payload, you can annotate it with #[default] to derive it:
#[derive(Default)]
enum Food {
#[default]
Sweet,
Salty,
}
In the case where the default variant does have a payload, you will have to implement Default on your enum manually:
enum Food {
Sweet(i32),
Salty,
}
impl Default for Food {
fn default() -> Food {
Food::Sweet(1)
}
}From rustc --explain E0665 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0308mismatched types
- E0277the trait bound is not satisfied
- E0599no method named X found in the current scope
- E0433failed to resolve
- E0643method `foo` has incompatible signature for trait
- E0644closure/coroutine type that references itself
- E0666nested `impl Trait` is not allowed
- E0689can't call method `neg` on ambiguous numeric type `{float}`
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?