Golang 报错 package xxx is not in GOROOT or GOPATH 或者 cannot find package “xxx“ in any of
GO111MODULE=”off”
在 GO111MODULE="off"
的条件下,并且写的代码不在 $GOPATH/src
下,也就是说下面的 main.go
不在$GOPATH/src
目录下面,同时我想要使用当前项目目录下的另一个 module
里面的可导出标识符(函数、变量等),但是这个模块 不是标准库
,或者说不在 GOROOT 里(一般我们不会修改 GOROOT 中的内容)

运行代码会报错
1 | main.go:4:2: cannot find package "module" in any of: |
解决方案: 设置 GOPATH
1 | go env -w GOPATH=~/test |
然后在 $GOPATH/src
目录下写

go 的编译器会在 $GOPATH/src
下面寻找对应的模块,src 下的每一个目录都可以对应一个模块,目录中的目录也可以是一个模块,如果,我们需要访问一个嵌套目录中的模块,比如下图

我们需要调用 module 目录中的 moduleA 模块,只需要使用
1 | import "module/moduleA" |
动图演示

GO111MODULE=”on”
在 GO111MODULE="on"
的条件下,我们直接调用写好的模块,如下图所示

会直接报错
1 | main.go:4:2: package module is not in GOROOT (/usr/local/go/src/module) |
解决方案
- 第一种方式:设置
GO111MODULE="off"
,然后像上面的那种方式一样设置GOPATH
- 第二种方式:使用
go mod
,如下

首先我们需要初始化一个 go.mod
,使用
1 | go mod init test |
然后我们引入模块的时候,以 test
(初始化时定义)开头,然后接模块路径,比如
1 | import "test/module" |
如果使用这种方式 Goland 报错,但是可以进行正常编译,那么可以删除当前目录下的
.idea
目录然后重启项目即可
如果我们想要引用嵌套模块也是一样的
1 | import "test/module/moduleA" |

动图演示

生活杂笔,学习杂记,偶尔随便写写东西。
Golang 报错 package xxx is not in GOROOT or GOPATH 或者 cannot find package “xxx“ in any of
https://junhaideng.github.io/2020/07/11/golang/fundamental/import-package/