struct's fields are all public? no access control?

Q. Schroll qs.il.paperinik at gmail.com
Mon Apr 5 20:30:49 UTC 2021


On Friday, 2 April 2021 at 15:35:03 UTC, mw wrote:
> https://run.dlang.io/is/xent7k
>
> ```D
> import std;
>
> struct Lady {
>     private int age;
>     int height;
>     float ageXHeight;
> }
>
> void main()
> {
>     Lady p;
>     p.age = 20;      // why can access private field here?
>     writeln(p.age);  // why can access private field here?
> }
> ```
>
> Is this a compiler bug, or by language design?

Have a look at [Access specifiers and 
visibility](https://wiki.dlang.org/Access_specifiers_and_visibility#Current_state_of_affairs_in_D). It has an error in the sense that `package` can be extended to super-packages. If you want to limit access, put your struct in a sub-module and place "friend" (in the C++ sense) functions in that sub-module. Then `public import` the sub-module in your original module. Now, `private` struct members are private in your sense. If you had `package` members, you might need the elaborate `package` [Visibility Attribute](https://dlang.org/spec/attribute.html#visibility_attributes).
> **From the spec**
> `package` may have an optional parameter in the form of a 
> dot-separated identifier list which is resolved as the 
> qualified package name. The package must be either the module's 
> parent package or one of its anscestors. If this optional 
> parameter is present, the symbol will be visible in the 
> specified package and all of its descendants.

For example `package(mw.pack)` makes the affected member(s) 
visible to `mw.pack` and all its sub-modules.

Unfortunately for unit testing and quick tests, D does not allow 
defining multiple modules in one file.


More information about the Digitalmars-d mailing list