patterngoMajor
Private fields and methods for a struct
Viewed 0 times
privatestructandmethodsforfields
Problem
In the following test code I would like to have both
Can I do this in Go?
Fields
mytype and the doPrivate method private, so that only members of mytype can access it, but not other types\functions in the scope of the mypackage package.Can I do this in Go?
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")
}Fields
size and hash as well as the doPrivate method should be encapsulated and no other type should have access to them.Solution
That's not how "privacy" works in Go: the granularity of privacy is the package.
If you really want only the members of
But that's not the usual practice. Whether Go is OOP or not is debatable but clearly the practice isn't to encapsulate the code by a struct like you seem to want to do. Usually a package is small enough to be coherent: if you don't want to access fields from within the package, don't access them.
If you really want only the members of
mytype to access some fields, then you must isolate the struct and the functions in their own package.But that's not the usual practice. Whether Go is OOP or not is debatable but clearly the practice isn't to encapsulate the code by a struct like you seem to want to do. Usually a package is small enough to be coherent: if you don't want to access fields from within the package, don't access them.
Context
Stack Overflow Q#22148143, score: 98
Revisions (0)
No revisions yet.