Encapsulating Private Fields and Methods for Structs in Go
In Go, achieving true encapsulation for both struct fields and methods is a matter of understanding variable scoping and visibility rules.
By convention, an identifier starting with a capital letter is exported and can be accessed outside the declaring package. Conversely, lowercase identifiers are only accessible within the package itself.
To privatize both the mytype struct and its doPrivate method, the following steps should be taken:
The resulting code:
// Package mypkg defines the private mytype struct and its methods. package mypkg type mytype struct { size string hash uint32 } // doPrivate can only be accessed by members of mytype. func (r *mytype) doPrivate() string { return r.size }
Now, only members of the mytype struct can access its private fields and methods. External types or functions within the mypkg package cannot directly access these private members.
The above is the detailed content of How to Encapsulate Private Fields and Methods in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!