导入的struct方法不起作用

汤姆:

如果我运行以下代码,则所有内容均可编译并正常运行:

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)
}
nvcnvn:

init()重命名Init()应该可以!
基本上,所有不以Unicode大写字母开头的内容(函数,方法,结构,变量)都将在其包中可见!

您需要从以下语言规范中了解更多信息:http : //golang.org/ref/spec#Exported_identifiers

相关位:

标识符可以被导出以允许从另一个包访问它。如果同时满足以下条件,则导出标识符:

  1. 标识符名称的第一个字符是Unicode大写字母(Unicode类“ Lu”);
  2. 标识符在包块中声明,或者是字段名或方法名。所有其他标识符都不会导出。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章