Skip to content

Rust: a constructor that leaves a struct-, enum- or type-parameter-typed field unset fails with E0277, since #480's Default::default() needs a Default the generator never derives #493

Open

Description

@matt-edmondson

What's wrong

#480 (fixing #344) writes each field a Rust constructor leaves unset as field: Default::default(). That only compiles if the field's type implements Default, and RustGenerator never derives Default on anything it writes:

  • Plain structs derive nothing (Coder/Languages/RustGenerator.cs:524-529).
  • Enums derive Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, but not Default (:2415).
  • An unconstrained type parameter gets no Default bound.

The code involved is WriteConstructorBody (:1869-1931, with the loop at :1906-1909) and InstanceFieldNames (:1936). The empty-initialiser path at :1893 and the base-struct field (BaseMemberName) go wrong the same way.

Repro

AST:

  • enum Mode { Off, On }
  • struct Inner { int v; }
  • struct Outer { Inner inner; Mode mode; int n; Outer() {} }

Generated Rust:

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mode { Off, On, }
pub struct Inner { pub v: i32, }
pub struct Outer { pub inner: Inner, pub mode: Mode, pub n: i32, }
impl Outer {
    pub fn new() -> Self {
        Self { inner: Default::default(), mode: Default::default(), n: Default::default() }
    }
}

rustc: error[E0277]: the trait bound 'Inner: Default' is not satisfied, and the same error for Mode.

A generic struct Holder<T> { T value; int count; Holder() {} } gives impl<T> Holder<T> { ... Self { value: Default::default(), ... } }. rustc: E0277: the trait bound 'T: Default' is not satisfied.

The other targets compile the same AST: C# writes public Outer() {}, Go writes Outer{}, and C writes Outer self = {0};.

Suggested fix

Pick one of these for structs and enums:

For a type parameter, add T: Default either to the impl's bounds or only to new's where-clause.

Acceptance criteria

  • RustGeneratedSourceCompilesTests cases compile and run for each of these, left unset by a constructor:
    • a struct-typed field
    • an enum-typed field
    • a base struct
    • an unconstrained generic field
  • Numeric and String fields generate the same code as today.

Activity

  1. matt-edmondson commented on Nov 12, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions