Private fields and methods for a struct

Solution 1:

In Go, an identifier that starts with a capital letter is exported from the package, and can be accessed by anyone outside the package that declares it.

If an identifier starts with a lower case letter, it can only be accessed from within the package.

If you need members in a type to only be accessed by members of that type, you then need to place that type and its member functions in a separate package, as the only type in that package.

Solution 2:

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.

Solution 3:

You can create an interface with the method you wish to expose and only access the object when wrapped into that interface.

package main

type mytype struct {
    size string
    hash uint32
}

// interface for exposed methods
type myinterface interface {
    do() string
}

// constructor (optional)
func newMytype(size string, hash uint32) myinterface {
    return &mytype{size, hash}
}

func (r *mytype) doPrivate() string {
    return r.size
}

func (r *mytype) do() string {
    return r.doPrivate()
}

func main() {
    // with constructor
    t := newMytype("100", 100)
    t.do()
    // t.doPrivate() // t.doPrivate undefined (type myinterface has no field or method doPrivate)

    // without constructor
    t2:= myinterface(&mytype{"100", 100})
    t2.do()
    // t.doPrivate() // t.doPrivate undefined (type myinterface has no field or method doPrivate)doPrivate)
}

https://play.golang.org/p/awjIIj8Kwms

Solution 4:

You cannot do this in Go. Visibility is on a per package level only. But you may split your package into two.