Encapsulating Private Fields and Methods for Structs
In Go, it's essential to understand the concept of visibility for fields and methods within structs. By default, fields and methods that begin with capital letters are considered exported and can be accessed by any external code or packages that import the package declaring the struct.
Consider the following code:
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 example, the Size and Hash fields, as well as the doPrivate method, are all exported due to their initial capital letters. This means that any code outside the mypackage package can access these members.
However, to encapsulate the doPrivate method and prevent external access, we can leverage Go's package visibility rules. By placing the mytype struct and its doPrivate method in a separate package, we can make them only accessible to types within that package.
Here's how we can achieve this:
// mytype.go package mytype type Type struct { Size string Hash uint32 } func (r *Type) doPrivate() string { return r.Size }
// mypackage.go package mypackage import "./mytype" func (r *mytype.Type) Do() string { return r.doPrivate() }
By separating the struct and its private method into a separate package, we ensure that only types within the mytype package can access the doPrivate method. Other packages, including mypackage, can still use the Do method to access the public members of the Type struct, but they cannot directly access the doPrivate method.
The above is the detailed content of How can I Encapsulate Private Fields and Methods in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!