如果我运行以下代码,则所有内容均可编译并正常运行:
package main
import "fmt"
type Point struct {
x, y int
}
func (p *Point) init() bool {
p.x = 5
p.y = 10
return true
}
func main() {
point := Point{}
point.init()
fmt.Println(point)
}
但是,当我将其移动Point struct
到$GOPATH
目录中的软件包时,会出现以下错误:point.init undefined (cannot refer to unexported field or method class.(*Point)."".init)
谁能向我解释为什么会这样?
当我将其Point struct
放入称为class
代码的程序包后,代码如下所示(错误在我调用该init
方法的第8行):
package main
import "fmt"
import "class"
func main() {
point := class.Point{}
point.init()
fmt.Println(point)
}
将init()重命名为Init()应该可以!
基本上,所有不以Unicode大写字母开头的内容(函数,方法,结构,变量)都将在其包中可见!
您需要从以下语言规范中了解更多信息:http : //golang.org/ref/spec#Exported_identifiers
相关位:
标识符可以被导出以允许从另一个包访问它。如果同时满足以下条件,则导出标识符:
- 标识符名称的第一个字符是Unicode大写字母(Unicode类“ Lu”);和
- 标识符在包块中声明,或者是字段名或方法名。所有其他标识符都不会导出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句