On Friday, March 29, 2024 4:50:53 PM MDT curiousprogramma08 via Digitalmars-d- learn wrote: > ```d > struct QueueNode > { > > private int data; > private QueueNode *next = null; > > this(int data) > { > this.data = data; > } > } > ``` > I also tried to write it like this too: > > ```d > struct QueueNode > { > > private: > int data; > QueueNode *next = null; > > public: > this(int data) > { > this.data = data; > } > } > ``` > (I will use readonly ```@property``` as only way to read them) > > But ```data``` and ```next``` can be changed and can be read from > outside of the structure. What to do to prevent fields from being > read and changed from outside the structure?
In D, a private symbol is private to the module, not the type. A package symbol is then private to the modules within that package. And a public symbol is then available to anything that imports the module that it's in. D does not provide a way to make anything within a module inaccessible to other code within that same module. The module is treated as the level of encapsulation. For the most part, this simplifies the code (e.g. friends aren't necessary, unlike in C++, and it's much easier to write unit tests which need to have access to a type's internals), and if your module is so large that you have to worry about code within a module accidentally accessing other code within that module, then your module is probably too large anyway. So, if don't want code to be able to access any of the private members of your QueueNode type, that code will need to be in a separate module rather than in the same module as the QueueNode type. - Jonathan M Davis