go mod init 报错 go: cannot determine module path for source directory,不需要指定包名也可以自动推导!

问题描述及解决

新建了一个test文件,进入后使用

go mod init

出现报错,报错内容:

go: cannot determine module path for source directory E:\GoWorks\src\Test (outside GOPATH, module path must be specified)
go mod init 报错 go: cannot determine module path for source directory,不需要指定包名也可以自动推导!_第1张图片

直接给了很简单的解释:“outside GOPATH, module path must be specified”,“在GOPATH之外,必须指定模块路径”。

因此执行时候带上文件夹名字就行了 :

go mod init Test

在这里插入图片描述

成功。

原因分析

之前也遇到过这个问题,当时是实习期间,mt看见了直接质问我“你的包名呢?”…菜的无处藏匿。
但我记得自己并不是每次都这样去做了,有时候我直接go mod init,也不会报错。但这次和之前那次也都遇到了报错…
所以这次记录一下他的原因。

根据给的提示:“outside GOPATH, module path must be specified”,“在GOPATH之外,必须指定模块路径”。

我的GOPATH是在set GOPATH=C:\Users\xxxxx\go,所以在此之外,自然需要指定。但为什么之前可以呢?我并不记得之前自己有在这个目录下新建的情况。
我搜索了半天,发现搜出来的都是需要带名称,怀疑自己。。好像曼德拉效应一般。。我明明记得一直是这样,结果发现难道一直是错的?

继续搜索,查阅了go mod 的官方help文档

PS E:\GoWorks\src\Test> go mod init help
go: creating new go.mod: module help
go: to add module requirements and sums:
        go mod tidy
PS E:\GoWorks\src\Test> go help mod init
usage: go mod init [module-path]

Init initializes and writes a new go.mod file in the current directory, in
effect creating a new module rooted at the current directory. The go.mod file
must not already exist.

Init accepts one optional argument, the module path for the new module. If the
module path argument is omitted, init will attempt to infer the module path
using import comments in .go files, vendoring tool configuration files (like
Gopkg.lock), and the current directory (if in GOPATH).

If a configuration file for a vendoring tool is present, init will attempt to
import module requirements from it.

See https://golang.org/ref/mod#go-mod-init for more about 'go mod init'.

其中提到“init accepts one optional argument, the module path for the new module. See Module paths for instructions on choosing a module path. If the module path argument is omitted, init will attempt to infer the module path using import comments in .go files, vendoring tool configuration files, and the current directory (if in GOPATH).
即"如果模块路径参数被省略,init将尝试推断模块路径。
在.go文件、vendoring工具配置文件中使用导入注释(如Gopkg.lock),以及当前目录(如果在GOPATH中)。"
也就是说,是可以不带参数,由系统进行推导的。
系统会根据当前的目录信息,进行推导。

回顾今天的操作,正好修改了一下环境变量:我删除了自己的用户变量,系统变量没变。

go mod init 报错 go: cannot determine module path for source directory,不需要指定包名也可以自动推导!_第2张图片

重新加上后,直接在新文件夹下go mod init,也可以了!

啊,那这样是为什么呢?
按理说我已经在系统变量设置过了,但为什么加到用户变量才行?
通过此文学习了二者差别,发现也不对啊——应该是优先找系统 之后才去用户…

再定睛一看——嗯…我知道了…我宣布这是我见到的一个很离谱且低级的错误了…
go mod init 报错 go: cannot determine module path for source directory,不需要指定包名也可以自动推导!_第3张图片

总结

设置对环境变量后,go mod init 是可以自动推导的!!!不一定需要指定包名了!!!

你可能感兴趣的:(莫名其妙的报错——我太傻了,golang,数据库,开发语言)