Saltar al contenido
TE108 · Tipos · error

No se puede derivar `Default`: campo sin valor por defecto

Un struct con `@derive(Default)` tiene un campo cuyo tipo no posee zero-value ni default explícito, por lo que no se puede sintetizar ninguna impl de `Default`.

Why this fires

A struct decorated with @derive(Default) has a field whose type has no zero value and no explicit default — @derive(Default) cannot synthesize a Default impl for it.

struct Point { x: int, y: int }

@derive(Default)
struct Shape {
    label: str,
    anchor: Point,
    //      ^^^^^ error[TE108]: cannot derive Default for 'Shape': field 'anchor'
    //             has no Default (give it an explicit default or implement
    //             Default for its type)
}

Point has no zero value of its own (it isn't a primitive and has no @derive(Default)/impl Default of its own), so Shape can't derive one either.

Fix it

1. Give the field an explicit default

@derive(Default)
struct Shape {
    label: str,
    anchor: Point = Point { x: 0, y: 0 },   // ok
}

2. Derive (or implement) Default for the field's type too

@derive(Default)
struct Point { x: int, y: int }

@derive(Default)
struct Shape {
    label: str,
    anchor: Point,                          // ok — Point now has a Default
}

See also

  • TE109 — a field's type can't be inferred from its default value.
  • TE107 — a struct-literal call site omits a required field.
  • /docs/data-structures#structs — field defaults and @derive(Default).

Véase también

Buscar en Zolo

9 resultados

en