skip to content

What does #[derive(Default)] generate for a Rust struct, and when does rustc refuse to compile it?

level: juniorimportance: must knowfreq 65%

answer

  1. one trait, one associated function
  2. built field by field
  3. zero, false, empty, None
  4. every field type must cooperate
  5. ..Default::default() fills the rest

basics

~20 s

It generates an impl Default whose default() calls Default::default() on every field, giving 0, false, empty strings and collections, and None. rustc rejects the derive with E0277 when any field's type does not implement Default.

solid answer

~40 s

`#[derive(Default)]` writes `impl Default for ServerConfig` with a `fn default() -> Self` that builds the struct from each field type's own `Default::default()`: `0` for integers, `false` for `bool`, an empty `String` and `Vec`, `None` for `Option<T>`. If one field's type has no `Default` impl, compilation fails with E0277, "the trait bound `Port: Default` is not satisfied", and you either derive `Default` on that type or write an impl by hand. A hand-written impl is also the answer when zero is the wrong starting value, such as a port that should be 8080. Callers then override a few fields with `ServerConfig { port: 8080, ..Default::default() }`. On a generic struct the derive also adds a `T: Default` bound, even when the fields would not need it.

code

rust · 20 lines
rust
use std::time::Duration;

#[derive(Debug, Default)]
struct ServerConfig {
    host: String,              // String::default() is ""
    port: u16,                 // 0
    workers: usize,            // 0
    tls: bool,                 // false
    timeout: Option<Duration>, // None
    allowed_origins: Vec<String>, // empty Vec
}

fn main() {
    let zero = ServerConfig::default();
    println!("{zero:?}");

    // Override two fields, take the rest from Default::default()
    let custom = ServerConfig { port: 8080, tls: true, ..Default::default() };
    println!("{} {} {:?}", custom.port, custom.tls, custom.timeout);
}

go deeper

for a junior

Recall that Default has one function, default(), that the derive fills each field from its type's default, and the values for integers, bool, String, Vec and Option. Show the ..Default::default() override.

for a middle

Explain that the derive calls each field type's Default rather than zeroing memory, which is why a field type without Default causes E0277, and name the fixes: derive on that type or write the impl.

for a senior

Spot the generic-bound trap, where the derive demands T: Default that the fields never needed, and know that ..Default::default() evaluates the whole default, so expensive defaults show up in hot paths.

for a principal

Frame Default as part of a type's public promise: once callers rely on it, its values are hard to change, so pick defaults that are safe in production rather than merely zero.

## No constructors, one trait Rust has no constructor syntax. A value is built with a struct literal such as `ServerConfig { port: 8080, .. }`, usually wrapped in an ordinary associated function. For the case "give me a sensible starting value and I will adjust it", the standard library offers the **`Default`** trait, declared in `core::default` and re-exported through the prelude, so it never needs a `use`. It has a `Sized` supertrait and exactly one required item: - `fn default() -> Self` returns a value of the implementing type. - It takes no arguments and returns `Self`, not `Result` or `Option`, so a default can never fail. - Because of the `Sized` supertrait, unsized types such as `str` or `dyn Trait` cannot implement it; `&str`, `String` and `Box<str>` can. You can call it as `ServerConfig::default()`, or as `Default::default()` and let type inference choose the implementation. ## What the derive writes `#[derive(Default)]` on a struct generates an `impl Default for ServerConfig` whose `default()` builds the struct field by field, calling each field type's own `Default::default()`. Nothing is zeroed in memory: every value comes from a trait call, which is why the field types matter. For the common std types the result is: | Field type | `Default::default()` | |---|---| | `u16`, `i64`, `usize` and the other integers | `0` | | `f32`, `f64` | `0.0` | | `bool` | `false` | | `char` | `'\x00'` | | `String` | `""` (empty, no allocation) | | `Vec<T>` | an empty vector, for any `T` | | `Option<T>` | `None`, for any `T` | | a tuple of up to 12 `Default` types | each element's default | The derive works the same way on tuple structs and unit structs. A field whose type is another struct that derives `Default` gets that struct's default, so defaults compose through nested configuration types. ## When rustc refuses The derive needs every field type to implement `Default`. If one does not, the generated code calls a method that does not exist and rustc stops with **E0277**. For `struct Port(u16);` used as a field it prints "the trait bound `Port: Default` is not satisfied" and points at the field. The fixes, in order of preference: 1. Derive `Default` on `Port` too, if its own field defaults make sense. 2. Write `impl Default for Port` by hand when they do not, for example to start at 8080 rather than 0. 3. Write `impl Default for ServerConfig` by hand and pick that field's value there. Putting `#[default]` on the field does not help: on stable that attribute is accepted only on unit variants of an enum, and on a field rustc rejects it with "the `#[default]` attribute may only be used on unit enum variants". Writing a default value next to a field (`port: u16 = 8080`) is also not stable Rust; rustc 1.99 reports E0658, "default values on fields are experimental". ## Overriding a few fields The everyday use is a literal that names the fields you care about and takes the rest from a default value: - `ServerConfig { port: 8080, tls: true, ..Default::default() }` builds a whole `ServerConfig` with `default()`, then takes `port` and `tls` from the literal and moves or copies every other field from that base value. - `default()` runs once for the entire struct, including the fields you overrode, so an expensive or side-effecting default is paid in full. - Every field must be visible where you write the literal; a private field makes it fail with E0451 outside the defining module. The rules of struct update syntax itself belong to the material on structs. ## Generic structs get an extra bound On a generic type, the derive adds a `Default` bound for each type parameter. `#[derive(Default)] struct Pool<T> { items: Vec<T> }` produces `impl<T: Default> Default for Pool<T>`, even though `Vec<T>` is `Default` for every `T`. The derive itself compiles; the error appears where you call `Pool::<Conn>::default()` for a `Conn` without `Default`, and rustc's help line reads: consider manually implementing `Default` to avoid undesired bounds caused by "imperfect derives". The fix is a hand-written `impl<T> Default for Pool<T>` that returns `Pool { items: Vec::new() }`. ## When to write the impl yourself - The zero value is wrong for the domain: a port of 0, a worker count of 0, an empty host. - A field type has no `Default` and you do not own it or do not want to give it one. - The derive would add a type-parameter bound the fields do not need. - The default is computed rather than a constant; keep that work cheap and infallible, because `default()` returns `Self` and runs implicitly inside `..Default::default()` and derived impls. Interviewers usually start from "how do you build a config struct when most fields keep their usual value", and the expected answer is `#[derive(Default)]` plus `..Default::default()`, with a hand-written impl wherever zero is the wrong starting point.

  • Why does #[derive(Default)] on struct Pool<T> { items: Vec<T> } fail for Pool<Conn> when Vec<Conn> already has a default?
    The derive generates `impl<T: Default> Default for Pool<T>`: it bounds every type parameter, not just the fields that need it. `Pool::<Conn>::default()` then fails with E0277 because `Conn` lacks `Default`, and rustc suggests implementing it manually. Writing `impl<T> Default for Pool<T> { fn default() -> Self { Pool { items: Vec::new() } } }` removes the bound.
  • Does ServerConfig { port: 8080, ..Default::default() } call default() for the field you overrode?
    Yes. The expression after `..` is a complete `ServerConfig` produced by one call to `default()`; the new value takes `port` from the literal and moves or copies the remaining fields from that base, and the base's own `port` is discarded. Any cost or side effect inside `default()` happens in full, for every field.

  • Every Rust struct gets a zero-filled default automatically, without a derive or an impl.
  • The derive leaves a field uninitialised when its type has no Default implementation.
  • On stable Rust you can write a default value next to a field, like port: u16 = 8080.
  • Putting #[default] on a struct field tells the derive which value to use.
  • The ..Default::default() base only constructs the fields the literal leaves out.
  • Deriving Default on a generic struct never adds bounds on its type parameters.