gpt4 book ai didi

oop - 导入的结构方法不起作用

转载 作者:IT王子 更新时间:2023-10-29 00:34:25 24 4
gpt4 key购买 nike

如果我运行以下代码,一切都会编译并运行良好:

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未导出的字段或方法类。(*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

相关位:

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name.All other identifiers are not exported.

关于oop - 导入的结构方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com