我对Golang有一些问题,包括包.我有那个结构
src/
??? hello_world
? ??? hello.go
? ??? math
? ??? add.go
Run Code Online (Sandbox Code Playgroud)
hello.go文件包含以下代码:
package main
import (
"fmt"
math "hello_world/math"
)
func main() {
fmt.Println("Hello World")
x := math.add(6, 5)
}
Run Code Online (Sandbox Code Playgroud)
并添加.go
package math
func add(x, y int) int {
return x + y
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,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".add
Run Code Online (Sandbox Code Playgroud)
GOPATH:
evgen@laptop:~/go/src/hello_world$ echo $GOPATH
/home/evgen/go
Run Code Online (Sandbox Code Playgroud)
如何解决?谢谢!
在包之外,只能访问和引用导出的标识符,即以大写字母开头的标识符.
所以最简单的解决方法是math.add()
通过将其名称更改为Add()
in 来导出函数math.go
:
func Add(x, y int) int {
return x + y
}
Run Code Online (Sandbox Code Playgroud)
当然,当你从以下方面提及时main.go
:
x := math.Add(6, 5)
Run Code Online (Sandbox Code Playgroud)
作为旁注,请注意,在导入hello_world/math
包时,您不必指定新名称来引用其导出的标识符:默认情况下,它将是其导入路径的最后一部分,因此这相当于您的导入:
import (
"fmt"
"hello_world/math"
)
Run Code Online (Sandbox Code Playgroud)