Encapsulating Private Fields and Methods in a Go Struct
In Go, the visibility of fields and methods within a struct is controlled by the first character of their names. Fields and methods that start with a capital letter are exported from the package and can be accessed by external code. Conversely, those that start with a lowercase letter are private to the package.
To restrict access to certain fields and methods within a struct, you can place the struct and its member functions in a separate package. This way, only the type defined in the package will have access to the private members.
For instance, in the provided example, you can create a new package for your mytype struct:
// mytype.go // Define the mytype struct with private fields and methods. package mytype type mytype struct { size string hash uint32 } func (r *mytype) doPrivate() string { return r.size }
As long as the mytype package does not import any other packages, the fields size and hash and the method doPrivate will remain private to mytype and inaccessible from outside the package.
The above is the detailed content of How can I make fields and methods private within a Go struct?. For more information, please follow other related articles on the PHP Chinese website!