andrew.fox
andrew.fox

Reputation: 7933

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.

Upvotes: 103

Views: 128932

Answers (6)

Michael Green
Michael Green

Reputation: 810

You can have private variables and functions in Go, but the trick is that you simply don't define them in the struct. Bind them to the call stack of a closure, and simply don't return them.

package main

import (
    "fmt"
)

type mytype struct {
    Do func() string
}

func MyType(size string, hash uint32) mytype {
    doPrivate := func() string {
        return size
    }
    return mytype{
        Do: func() string {
            return doPrivate()
        },
    }
}

func main() {
    instance := MyType("100", 100)
    fmt.Println(instance.Do())
}

Upvotes: 1

Lex
Lex

Reputation: 800

In one module there can be any number of packages.

Public/Private works only across one package.
All public fields, methods and functions starts with uppercase char.
All private fields, methods and functions starts with lowercase char.

To add package to your module or program just create a lowercase folder and add package name to all files inside. Here is the example.

./main.go
./foo/foo.go
./foo/MyStruct.go

file ./foo/foo.go:

package foo

import "fmt"

func SomePublicFuncInFoo() {
    somePrivateFuncInFoo()
}

func somePrivateFuncInFoo() {
    fmt.Println("somePrivateFuncInFoo call")
}

file ./foo/MyStruct.go:

package foo

import "fmt"

type MyStruct struct {
    MyPublicField  string // starts with uppercase char
    myPrivateField string // starts with lowercase char
}

func NewMyStruct(publicField string, privateField string) *MyStruct {
    return &MyStruct{
        MyPublicField:  publicField,  
        myPrivateField: privateField, 
    }
}

func (self *MyStruct) SomePublicMethod() {
    self.privateMethod()
}

func (self *MyStruct) privateMethod() {
    fmt.Println("MyStruct", self.MyPublicField, self.myPrivateField)
}

file ./main.go:

package main

import (
    "fmt"
    "{your-module-name}/foo" // this line should be added by your IDE
)

func main() {

    foo.SomePublicFuncInFoo()

    myStruct := foo.NewMyStruct("string1", "string2")
    fmt.Println("myStruct.MyPublicField=", myStruct.MyPublicField)

    myStruct.SomePublicMethod()
}

Upvotes: 7

Farshid T
Farshid T

Reputation: 2293

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

Upvotes: 54

nos
nos

Reputation: 229108

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.

Upvotes: 131

Denys Séguret
Denys Séguret

Reputation: 382150

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.

Upvotes: 97

Volker
Volker

Reputation: 42413

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

Upvotes: 15

Related Questions