调用 struct 函数会导致“无法引用未导出的字段或方法" [英] Invoking struct function gives "cannot refer to unexported field or method"
本文介绍了调用 struct 函数会导致“无法引用未导出的字段或方法"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的结构:
type MyStruct struct {
Id string
}
和功能:
func (m *MyStruct) id() {
// doing something with id here
}
我还有另一个这样的结构:
Also I have another structure like this:
type MyStruct2 struct {
m *MyStruct
}
现在我有一个函数:
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?
推荐答案
来自 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:
- 标识符名称的第一个字符是Unicode大写字母(Unicode类Lu");和
- 标识符是在包块中声明的,或者是字段名或方法名.
- 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.
示例:
type MyStruct struct {
id string
}
func (m *MyStruct) Id() {
// doing something with id here
}
//then
func foo(str *MyStruct2) {
str.m.Id()
}
这篇关于调用 struct 函数会导致“无法引用未导出的字段或方法"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文