我有这样的结构:
type MyStruct struct {
Id string
}
和函数:
func (m *MyStruct) id() {
// doing something with id here
}
我还有一个这样的结构:
type MyStruct2 struct {
m *MyStruct
}
现在我有一个函数:
func foo(str *MyStruct2) {
str.m.id()
}
但是我在编译时遇到错误:
str.m.id undefined (cannot refer to unexported field or method mypackage.(*MyStruct)."".id
如何正确调用这个函数?
最佳答案
来自 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.
所以基本上只有以大写字母开头的函数/变量才能在包外使用。
例子:
type MyStruct struct {
id string
}
func (m *MyStruct) Id() {
// doing something with id here
}
//then
func foo(str *MyStruct2) {
str.m.Id()
}
关于pointers - 调用结构函数给出 "cannot refer to unexported field or method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866159/