调用golang结构函数给出“不能引用未导出的字段或方法” [英] Invoke golang struct function gives "cannot refer to unexported field or method"
问题描述
type MyStruct struct {
Id string
}
和函数:
func(m * MyStruct)id(){
//在这里用id做某事
}
另外我还有另外一个这样的结构:
type MyStruct2 struct {
m * MyStruct
}
现在我有一个函数:
func foo(str * MyStruct2){
str.m.id()
}
但是我在编译时遇到错误:
str.m.id undefined(不能引用未导出的字段或方法mypackage。(* MyStruct)。。id
如何正确调用此函数?
谢谢
从 http://golang.org/ref / spec#Exported_identifiers :
$ b
一个标识符可以被导出以允许从另一个
包中访问它。如果同时输出标识符:
- 标识符名称的第一个字符是 Unicode大写字母( Unicode类Lu);
标识符是在包区块中声明的,或者是字段名称或方法名称。
因此,基本上只有以大写字母开头的函数/变量才能用于包之外。
示例:
type MyStruct struct {
id string
}
func(m * MyStruct)Id (){
//在这里用id做一些事
}
//然后
func foo(str * MyStruct2){
str.m.Id()
}
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
解决方案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() }
这篇关于调用golang结构函数给出“不能引用未导出的字段或方法”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!