Description
Given the following code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6fd5b067e894e9be655bd28918386f7e
struct Struct {
id: usize,
option: Option<usize>,
}
fn create(id: usize) -> Struct {
Struct {
id,
Some(1),
}
}
fn main() {
let _ = create(1);
}
The current output is:
error: expected one of `,` or `}`, found `(`
--> src/bin/lib.rs:9:13
|
7 | Struct {
| ------ while parsing this struct
8 | id,
9 | Some(1),
| ^ expected one of `,` or `}`
error[E0063]: missing field `option` in initializer of `Struct`
--> src/bin/lib.rs:7:5
|
7 | Struct {
| ^^^^^^ missing `option`
The first message is about an expected comma or closing curly brace, which is not terribly helpful - we do want to initialize more than one member, so why would we be required to end the instantiation after the id,
?
The "missing field option
" message will perhaps prompt the reader to explicitly name the option
member, like this:
fn create(id: usize) -> Struct {
Struct {
id,
option: Some(1),
}
}
and this will solve the problem, which may trick the reader into believing that only "simple" initializers can be used when instantiating the Struct
(and Some(1)
would not be considered "simple").
Reading the output of rustc --explain E0063
does not help, because it says "A struct's or struct-like enum variant's field was not provided". The actual problem is that while the id
member can use the "field init shorthand" (because it is called the same as the create
's argument), the option
member cannot, but there's no such hint neither in the compiler messages nor in the rustc --explain E0063
.
Ideally some mention of the "field init shorthand" should be provided either in the messages, or in the output of rustc --explain
.