无法导入Go包。

huangapple go评论83阅读模式
英文:

Not able to import Go packages

问题

我想使用这个包:github.com/go-sql-driver/mysql

我尝试了以下命令:

go get -u github.com/go-sql-driver/mysql

它执行成功了,但是当我导入这个包并运行代码时,出现了错误:

main.go:12:2: 没有必需的模块提供了包 github.com/go-sql-driver/mysql:在当前目录或任何父目录中找不到 go.mod 文件;请参阅 'go help modules'
英文:

I want to use this package: github.com/go-sql-driver/mysql

I tried with:

go get -u github.com/go-sql-driver/mysql

It went right, but when I'm importing the package and running the code its gives me an error:

main.go:12:2: no required module provides package github.com/go-sql-driver/mysql: go.mod file not found in current directory or any parent directory; see 'go help modules'

答案1

得分: 4

在项目根目录下运行以下命令:

go mod init example.com/your-project-name

它将创建一个名为 go.mod 的文件,内容如下:

module example.com/your-project-name

go 1.15

然后运行以下命令:

go get -u github.com/go-sql-driver/mysql
英文:

In project root directory run

go mod init example.com/your-project-name

It will create go.mod file

module example.com/your-project-name

go 1.15

Then run

go get -u github.com/go-sql-driver/mysql

答案2

得分: 0

编辑:正如rustyx在评论中所说,这种方法已经过时,你可能需要考虑更新的方法。

如果你的GOROOTGOPATH环境变量设置正确,你可以不使用go.mod文件。要做到这一点,你可以参考以下链接:
https://stackoverflow.com/questions/7970390/what-should-be-the-values-of-gopath-and-goroot

此外,你需要确保你的IDE/文本编辑器也能识别这两个变量。
注意:对于IDE(如Goland),你可能需要手动设置。对于文本编辑器(例如vscode),你只需重新加载项目,就可以解决问题。

完成这些步骤后,你可以验证你的$GOPATH/github.com/go-sql-driver/mysql/目录中是否存在内容。如果不存在,你可以重新运行go get -u github.com/go-sql-driver/mysql命令,重新加载编辑器,然后应该就没问题了。

英文:

EDIT: As rustyx said in the comment, this is a deprecated approach and you might want to consider newer ones

You can do without the go.mod if your GOROOT and GOPATH environment variables are setted correctly
To do so, you can refer to
https://stackoverflow.com/questions/7970390/what-should-be-the-values-of-gopath-and-goroot

Also, you need to ensure that your IDE/text editor also recognize those two variables.
Note: In the case of an IDE (such as Goland), you might need to set it up manually. In the case of a text editor (ex: vscode), you can simply reload your project and it should do the trick.

Once this is done, you can validate that the content of your $GOPATH/github.com/go-sql-driver/mysql/ is present. If not, you can rerun your go get -u github.com/go-sql-driver/mysql command, reload your editor, and you should be alright

huangapple
  • 本文由 发表于 2021年9月20日 19:27:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/69253648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定