Unable to Create Private Fields and Methods for Structs in a Package
Question:
Is it possible to set a struct's field and method as private within a Go package, accessible only by members of that struct, but not by other package functions or external code?
Context:
Consider the following code snippet:
package mypackage type mytype struct { size string hash uint32 } func (r *mytype) doPrivate() string { return r.size } func (r *mytype) Do() string { return doPrivate("dsdsd") }
In this case, the size and hash fields and the doPrivate method should be encapsulated within mytype, inaccessible to other types.
Answer:
While Go allows you to export or hide an identifier based on its capitalization, the concept of private class members or data hiding does not exist in Go.
By convention, exported identifiers (initialized with a capital letter) are intended for public use within a package. Conversely, unexported identifiers (initialized with a lowercase letter) have restricted access within that package.
However, within a given package, there is no way to further restrict access to struct members beyond that package scope. To achieve data encapsulation, the suggested approach is to create a separate package where the entire struct and its associated methods are the only elements defined within that package.
The above is the detailed content of Can you make struct fields and methods private in Go packages?. For more information, please follow other related articles on the PHP Chinese website!