Why this fires¶
A struct literal (Struct { ... }) omits a field that has no default value and no zero-value fallback. Every non-defaultable field must be provided explicitly at construction time.
struct User {
name: str,
age: int,
}
let u = User { name: "Ana" }
// ^^^^^^^^^^^^^^^^^^^^ error[TE107]: missing field 'age' in construction of 'User'Fix it¶
1. Provide the missing field¶
let u = User { name: "Ana", age: 30 } // ok2. Give the field a default¶
If the field usually has the same value, declare a default so callers can omit it:
struct User {
name: str,
age: int = 0,
}
let u = User { name: "Ana" } // ok — age defaults to 03. Spread from an existing value¶
A trailing ..expr spread contributes its fields to construction coverage, so omitted fields are filled from expr instead of erroring:
struct User { name: str, age: int }
fn rename(u: User, new_name: str) -> User {
return User { name: new_name, ..u } // ok — `age` comes from `u`
}See also¶
TE108— a field can't get a@derive(Default)default because its own type has noDefault.TE109— a field's type can't be inferred from its default value.TE128— spread source (..expr) must be a struct or record.- /docs/data-structures#structs — struct construction and field defaults.