1. 代码结构
demo
文件夹下有两个文件,分别为 hello.go
和 main.go
,结构如下:
wohu@wohu:~/GoCode/src$ tree demo/
demo/
├── hello.go
└── main.go
0 directories, 2 files
wohu@wohu:~/GoCode/src$
hello.go
文件内容为:
package main
import "fmt"
func hello() {
fmt.Println("hello, world")
}
main.go
文件内容为:
package main
func main() {
hello()
}
2. 运行代码
wohu@wohu:~/GoCode/src/demo$ go run main.go
# command-line-arguments
./main.go:4:2: undefined: hello
按道理讲同一个包内的函数是可以互相调用访问的,但是此处报错,提示 undefined: hello
。
3. 问题原因
Go
中 main
包默认不会加载其他文件, 而其他包都是默认加载的。如果 main
包有多个文件,则在执行的时候需要将其它文件都带上,即执行 go run *.go
。
如下所示:
wohu@wohu:~/GoCode/src/demo$ go run *.go
hello, world
wohu@wohu:~/GoCode/src/demo$
4. VSCode 中配置
在 VSCode
的 .vscode
目录下创建 settings.json
文件, 并添加如下内容:
{
"code-runner.executorMap": {
"go": "cd $dir && go run .",
},
"code-runner.executorMapByGlob": {
"$dir\\*.go": "go"
}
}
然后在 VSCode GUI
界面提供的 Run Code
按钮,会有如下输出:
[Running] cd "/home/wohu/GoCode/src/demo/" && go run .
hello, world
[Done] exited with code=0 in 0.177 seconds
如果没有在 settings.json
文件中增加以上内容的话,在 VSCode GUI
界面提供的 Run Code
按钮,会有如下错误:
[Running] go run "/home/wohu/GoCode/src/demo/main.go"
# command-line-arguments
src/demo/main.go:4:12: undefined: hello
[Done] exited with code=2 in 0.158 seconds
注意两者运行命令之间的区别:
go run "/home/wohu/GoCode/src/demo/main.go
和
cd "/home/wohu/GoCode/src/demo/" && go run .