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:

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

Need Your Help

data-content not working when clicked

javascript jquery html5

There is a javascript and jquery for which I need your help:

FileInputStream / FileOutputStream blocking?

java swing event-dispatch-thread jprogressbar

I have the following code which successfully copies a file. However, there are two problems with it:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.