go

Private fields and methods for a struct


In the following test code I would like to have both 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 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.