41

Why does ParseBoolError have the _priv field:

pub struct ParseBoolError {
    _priv: (),
}

I don't think that the _priv field is used.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
m-bat
  • 579
  • 4
  • 9

1 Answers1

42

You can't create an instance of a struct if it has private fields. This is just a trick to prevent ParseBoolError from being constructed in user code.

One reason to do this is for forwards compatibility. If users could create it with:

let error = ParseBoolError {};

then a future version of ParseBoolError couldn't add fields without breaking that code.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • 3
    There's now an attribute that does this as well: [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute). The `non_exhaustive` attribute prevents any other crate from creating an instance of your struct, on the basis that it may change in the future. On enums, it requires you to always specify `_` in `match` statements. – Dev Aug 11 '20 at 04:58
  • 1
    @Dev Doesn't sound that good to me... basically you force people to use `_`, now when they upgade library they do not get any warning yet their code will not handle sensibly the new constructors... not terribly useful. – Bakuriu Aug 11 '20 at 10:11
  • @Bakuriu It's useful for structs – Dev Aug 12 '20 at 11:03