Skip to content

Missing field error in initializer for struct with inaccessible fields #87872

Closed
@gheoan

Description

@gheoan

Given the following code:

// in file a.rs
#![crate_type = "lib"]

pub struct X {  
  pub f: u32, // remove the field f to get a different error message
  pub(crate) g: u32,
}

// this is to prevent a warning that g is not used
impl X {
  pub fn value(self) -> u32 { self.g }
}
// in file b.rs
#![crate_type = "bin"]

extern crate a;

fn main() {
  let x = a::X {};
  x.value();
}

Using rustc a.rs followed by rustc -L . b.rs, the current output is:

error[E0063]: missing fields `f` and `g` in initializer of `X`
 --> b.rs:6:11
  |
6 |   let x = a::X {};
  |           ^^^^ missing `f` and `g`

Ideally the output should look like:

error: cannot construct `X` with struct literal syntax due to inaccessible fields
 --> b.rs:6:11
  |
6 |   let x = a::X {};
  |           ^^^^

The rationale is the same as for #76077. Following the suggestion provided by the compiler will lead to another error. This can be frustrating with structs that have a large number of fields or fields with complex types, since the effort of adding those fields to the struct literal is in vain.

By removing the field f from the struct, the compiler is reporting that X cannot be constructed, as expected.

Tested on both rustc 1.56.0-nightly (574d37568 2021-08-07) and rustc 1.52.0-nightly (4a8b6f708 2021-03-11).

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions