go故障排查集锦

问题1:创建main.go时,提示“GOROOT is not defined”?

排查思路:

1)查询GOROOT变量,并验证是否正确;
    go env |findstr GOROOT

 

2)查询GOPATH变量,并验证是否正确;
    go env |findstr GOPATH

3)进入终端,直接测试是否能编译运行程序

 初步结论:golang的配置问题。

The selected directory is not a valid home for Go SDK --->golang默认的窗口目录是存放编译器的目录;

GOROOT是go的安装路径,windows下当你安装好go之后会自动设置该变量,但其他IDE(如:golang)启动后需要进行go SDK的路径设置,一般本地没有SDK,因此需要下载安装go版本的SDK并存放在指定路径;

 解决方法:从本地加载或直接下载对应版本的go sdk。

 

 

问题2:编译go程序失败?

Error: Run after the build is not possible

The 'main' file has the non-main package or does not contain the 'main' function

 10:52 Error running 'go build test1.go': Cannot run program "C:\Users\chalon\AppData\Local\Temp\GoLand\___go_build_test1_go.exe" (in directory "C:\Users\chalon\GolandProjects\go_test1"): CreateProcess error=216, 该版本的 %1 与你运行的 Windows 版本不兼容。请查看计算机的系统信息,然后联系软件发布者。

原因分析:没有main包;

解决方法:声明为main包即可。

 

 

 问题3:编译go程序失败?

10:59 Error running 'go build test1.go': Cannot run program "C:\Users\chalon\AppData\Local\Temp\GoLand\___go_build_test1_go.exe" (in directory "C:\Users\chalon\GolandProjects\go_test1"): CreateProcess error=5, 拒绝访问。

原因分析:go程序编译成功,但不能访问执行。

解决方法:执行受阻,设置安全规则即可。

 

 问题4:无法编译go程序,提示:

Build Error: go build -o e:\go\src\1go\1day\1_hello\__debug_bin.exe -gcflags all=-N -l .
go: go.mod file not found in current directory or any parent directory; see 'go help modules' (exit status 1)

原因分析:未发现go.mod;

解决方法:切换至项目目录下,执行go mod init命令,初始化项目即可产生go.mod;

 

 

问题4:无法编译go程序?

Build Error: go build -o e:\go\src\1go\1day\5_main_outside_function\main\__debug_bin.exe -gcflags all=-N -l .

main_outside_function.go:4:2: invalid import path: "E:/go/src/1go/1day/5_main_outside_function/add" (exit status 1)

原因分析:main在引入add包时,路径出错。

解决方法:引入目录必须从$GOPATH/src后开始计算,修改go env参数,并在项目目录下初始化mod;

 

 

 

 

 

 

问题5:无法编译go程序?

F:\>go build test1.go
# command-line-arguments
.test1.go:5:1: syntax error: non-declaration statement outside function body

原因分析:go程序中main()必须声明或调用。

解决方法:添加main()函数。

package main

import "fmt" 

func main(){
	fmt.Println("hello world!")
}

 

问题6:无法编译go程序?

GOROOT=null #gosetup
GOPATH=E:\go;C:\Users\chalon\go #gosetup
Cannot run program "\bin\go.exe" (in directory "E:\go"): CreateProcess error=2, 系统找不到指定的文件。
Compilation finished with exit code 126

原因分析:缺少go.mod;

解决方法:在项目下创建go.mod。

 

问题7、无法编译main.go?

 .\hello.go:5:2: undefined: test_pipe

原因分析:main.go无法解析其他依赖包中的函数。

解决方法:同时运行main.go及依赖文件。

 

问题8、vscode无法编译go程序?

 

 

fatal error: all goroutines are asleep - deadlock!

原因分析:切换为终端运行程序,查看原因。pipe管道先传递了4个参数后,引发了阻塞。

解决方法:注释行pipe<-4即可。

 

 

问题9、go程序未执行完毕就退出?

原因分析:main()会启动一个goroute,而test_goroute()会并发启动100个goroute,main执行完毕后不再执行test_goroute()的goroute线程。 

解决方法:main()中添加等待时间即可。

下图中在添加add的goroute后,并发执行main()的goroute完成后不会立即退出,其原因add未执行完毕会导致pipe无法从管道取到值,就不能完成main()的执行,此时无需再main()中添加时间等待。

 

 

posted on 2021-08-17 11:11  chalon  阅读(4168)  评论(0编辑  收藏  举报