Go – Invoking struct function gives “cannot refer to unexported field or method”

gopointersstruct

I have a structure something like this:

type MyStruct struct {
    Id    string
}

and function:

func (m *MyStruct) id() {
   // doing something with id here
}

Also I have another structure like this:

type MyStruct2 struct {
    m *MyStruct
}

Now I have a function:

func foo(str *MyStruct2) {
    str.m.id()
}

But I'm getting error in compile time:

str.m.id undefined (cannot refer to unexported field or method mypackage.(*MyStruct)."".id

How can I call this function correctly?

Best Answer

From http://golang.org/ref/spec#Exported_identifiers:

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name.

So basically only functions / variables starting with a capital letter would be usable outside the package.

Example:

type MyStruct struct {
    id    string
}

func (m *MyStruct) Id() {
   // doing something with id here
}

//then

func foo(str *MyStruct2) {
    str.m.Id()
}
Related Topic