> 文章列表 > ‘go install‘ requires a version when current directory is not in a module

‘go install‘ requires a version when current directory is not in a module

‘go install‘ requires a version when current directory is not in a module

背景

安装好环境之后,跑个helloworld看看

目录结构

workspacepathsrchellohelloworld.go

代码:

package mainimport "fmt"func main() {  fmt.Println("Hello World")
}

1.使用 go run 命令 - 在命令提示符旁,输入 go run workspacepath/src/hello/helloworld.go

上述命令中的 workspacepath 应该替换为你自己的工作区路径(Windows 下的 C:/Users/YourName/go,Linux 或 Mac 下的 $HOME/go)。

在控制台上会看见 Hello World 的输出。

2.使用 go install 命令 - 运行 go install hello,接着可以用 workspacepath/bin/hello 来运行该程序。

上述命令中的 workspacepath 应该替换为你自己的工作区路径(Windows 下的 C:/Users/YourName/go,Linux 或 Mac 下的 $HOME/go)。

当你输入 go install hello 时,go 工具会在工作区中搜索 hello 包(hello 称之为包)。接下来它会在工作区的 bin 目录下,创建一个名为 hello(Windows 下名为 hello.exe)的二进制文件。运行 go install hello 后,其目录结构如下所示:

workspacepathbinhellosrchellohelloworld.go

go install指令作用于文件夹,go语言称之为“包”。

接下来聊聊遇到的报错

使用 go 1.18,在 src 文件夹执行指令时出现该报错:
go: 'go install' requires a version when current directory is not in a module
‘go install‘ requires a version when current directory is not in a module
按照提示继续执行 go install hello@latest,报另一个错:
missing dot in first path element
‘go install‘ requires a version when current directory is not in a module
从go 1.17 开始,官方用 go install 代替 go get 安装依赖。我的版本是 go 1.18 。显然我这里跟更新依赖没关系,我只想单纯打包一下。

看了下官方教程,只教了 go run

官方的教程只用 go run
‘go install‘ requires a version when current directory is not in a module
‘go install‘ requires a version when current directory is not in a module

这里提供一个解决方法:

  1. 进入 hello 文件夹,生成 go.mod
cd hello go mod init 

输出 go: creating new go.mod: module hello,同时 hello 文件夹内新增 go.mod 文件

  1. 在hello文件夹内执行 go install
go install 或者指定模块名go install hello 

注意,模块名一定要对应 go.mod 文件内的 module name 。

如果不对应,会报错。比如

go.mod 文件用 hello1

module hello1go 1.18

那么执行 go mod hello 会报错 package hello is not in GOROOT

  1. 执行成功之后,你会看到 $GOPATH/bin 目录中生成hello,并且是可以运行输出的
cd $GOPATH/bin/
./hello 

至此问题解决。

总结:

  1. module name 和 文件夹名称是解耦的,文件夹名可以是 hello123,module name 取 hello 也可
  2. go install xxx ,一定要和 module name 对应;bin目录生成文件的命名也是 module name

希望对你有帮助

完。