我对Golang有一些问题,包括包裹。我拿到了那本书
src/
├── hello_world
│ ├── hello.go
│ └── math
│ └── add.gohello.go文件包含以下代码:
package main
import (
"fmt"
math "hello_world/math"
)
func main() {
fmt.Println("Hello World")
x := math.add(6, 5)
}和add.go
package math
func add(x, y int) int {
return x + y
}当我做go run hello go时,我看到:
evgen@laptop:~/go/src/hello_world$ go run hello.go
# command-line-arguments
./hello.go:10: cannot refer to unexported name math.add
./hello.go:10: undefined: "hello_world/math".addGOPATH:
evgen@laptop:~/go/src/hello_world$ echo $GOPATH
/home/evgen/go怎么修呢?谢谢你!
发布于 2015-10-04 10:00:02
在包之外,只能到达和引用导出的标识符,即以大写字母开头的标识符。
因此,最简单的解决方法是通过将math.add()函数的名称更改为math.go中的Add()来导出它
func Add(x, y int) int {
return x + y
}当然,当您从main.go中引用它时
x := math.Add(6, 5)另外,请注意,在导入您的hello_world/math包时,您不必指定一个新名称来引用其导出标识符:默认情况下,它将是导入路径的最后一部分,因此这相当于您的导入:
import (
"fmt"
"hello_world/math"
)发布于 2016-08-10 23:37:31
将希望其他函数读取的包中的函数大写如下:
func Add(x, y int) int {
return x + y
}然后在hello.go中这样调用它:
x := math.Add(6, 5)保持较低的大小写确实有其目的,特别是如果您想保护它不被无意中在包外使用。
发布于 2016-04-16 01:25:47
在调用Add中的主函数时,不要使用以下内容
x := math.Add(6 + 5)相反,请使用这个
x := math.Add(6, 5)https://stackoverflow.com/questions/32932199
复制相似问题