Invoke golang struct function gives “cannot refer to unexported field or method”
I have a golang 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?
Thank you
Answers
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:
- the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- 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() }