调用struct函数会给出“无法引用未导出的字段或方法". [英] Invoking struct function gives "cannot refer to unexported field or method"
本文介绍了调用struct函数会给出“无法引用未导出的字段或方法".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似这样的结构:
I have a structure something like this:
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
如何正确调用此函数?
推荐答案
来自 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屋!
查看全文