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

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()
}

Leave a Comment