Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum struct field names with leading underscore cause compiler errors #34

Open
DavidAntliff opened this issue May 17, 2024 · 0 comments

Comments

@DavidAntliff
Copy link

Please consider this example:

pub struct Data {}

#[subenum(Bar)]
pub enum Foo {
    #[subenum(Bar)]
    Baz { data: Data },
}

This compiles, as expected.

Consider if the data field of the Baz struct variant is renamed to _data, with a leading underscore:

pub struct Data {}

#[subenum(Bar)]
pub enum Foo {
    #[subenum(Bar)]
    Baz { _data: Data },
}

The compiler now issues a set of errors:

error[E0026]: variant `Bar::Baz` does not have a field named `data`
  --> src/model/mod.rs:57:11
   |
57 |     Baz { _data: Data },
   |           ^^^^^ variant `Bar::Baz` does not have this field

error: pattern requires `..` due to inaccessible fields
  --> src/model/mod.rs:53:1
   |
53 | #[subenum(Bar)]
   | ^^^^^^^^^^^^^^^
   |
   = note: this error originates in the attribute macro `subenum` (in Nightly builds, run with -Z macro-backtrace for more info)
help: ignore the inaccessible and unused fields
   |
57 |     Baz { _data, ..: Data },
   |                ++++

error[E0559]: variant `Foo::Baz` has no field named `data`
  --> src/model/mod.rs:57:11
   |
57 |     Baz { _data: Data },
   |           ^^^^^ `Foo::Baz` does not have this field
   |
   = note: all struct fields are already assigned

error[E0026]: variant `Foo::Baz` does not have a field named `data`
  --> src/model/mod.rs:57:11
   |
57 |     Baz { _data: Data },
   |           ^^^^^ variant `Foo::Baz` does not have this field

error[E0559]: variant `Bar::Baz` has no field named `data`
  --> src/model/mod.rs:57:11
   |
57 |     Baz { _data: Data },
   |           ^^^^^ `Bar::Baz` does not have this field
   |
   = note: all struct fields are already assigned

Something isn't quite right here.

What are the use-cases for naming a field like this? One is when creating "uninstantiable" enum variants, for example:

pub struct Private {
    _private: (),
}

#[subenum(Bar)]
pub enum Foo {
    #[subenum(Bar)]
    Baz { _private: Private },
}

The convention is to use a leading underscore for such private fields, but in this case it is not possible. The workaround is trivial though - just use private rather than _private as the field name.

So this is a minor issue, but perhaps surprising when encountered for the first time.

subenum = "1.1.2"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant