golang 同一个包中函数互相调用报错 undefined 以及在 VSCode 中配置右键执行整个包文件
生活随笔
收集整理的這篇文章主要介紹了
golang 同一个包中函数互相调用报错 undefined 以及在 VSCode 中配置右键执行整个包文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 代碼結構
demo 文件夾下有兩個文件,分別為 hello.go 和 main.go ,結構如下:
wohu@wohu:~/GoCode/src$ tree demo/
demo/
├── hello.go
└── main.go0 directories, 2 files
wohu@wohu:~/GoCode/src$
hello.go 文件內容為:
package mainimport "fmt"func hello() {fmt.Println("hello, world")
}
main.go 文件內容為:
package mainfunc 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 .
總結
以上是生活随笔為你收集整理的golang 同一个包中函数互相调用报错 undefined 以及在 VSCode 中配置右键执行整个包文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习入门(13)— Affine 仿
- 下一篇: 晶珠景天祛斑胶囊产品是否真的能去斑