跳到主要内容

问题

golang 同一个包中函数互相调用报错 undefined

demo 文件夹下有两个文件,分别为 hello.go 和 main.go ,结构如下:

demo/
├── hello.go
└── main.go

文件内容如下:

hello.go
package main

import "fmt"

func hello() {
fmt.Println("hello, world")
}
main.go
package main

func main() {
hello()
}

允许代码后报错:./main.go:4:2: undefined: hello

原因:Go 中 main 包默认不会加载其他文件, 而其他包都是默认加载的。

解决方法:

  1. 执行 go run main.go hello.go