Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define a struct with single private field of unit type?

Tags:

rust

Why does ParseBoolError have the _priv field:

pub struct ParseBoolError {
    _priv: (),
}

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

like image 524
m-bat Avatar asked Aug 10 '20 10:08

m-bat


People also ask

Can struct be private in C#?

Struct members, including nested classes and structs, can be declared public , internal , or private . Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private .

Are struct fields private rust?

In a normal scenario, the visibility of the struct in Rust is private and it can be made public by making use of the pub modifier. It should be noted that this case of visibility only makes sense when we are trying to access the struct fields from outside the module, from where it is defined.


1 Answers

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.

like image 76
Peter Hall Avatar answered Oct 28 '22 02:10

Peter Hall