无法导入包

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

GO - Could not import packages

问题

我使用的是Go 1.19和VScode 1.69.2。

当我从第二个Go文件中导入一个包时,我总是得到以下错误消息:

导入packages/calculator(没有所需的模块提供包"packages/calculator")

我将我的GOPATH设置为我的工作空间,我的GOROOT设置为usr/local/go。

无法导入包

无法导入包

无法导入包

无法导入包

无法导入包

有人有解决这个问题的想法吗?

英文:

I use Go 1.19 and VScode 1.69.2

I get always this error message by importing a package from a second go file:

> import packages/calculator (no required module provides package
> "packages/calculator")

I set my GOPATH to my workingspace and my GOROOT is set to usr/local/go

无法导入包

无法导入包

无法导入包

无法导入包

无法导入包

has anyone an idea to fix this problem?

答案1

得分: 1

使用模块来管理依赖关系。官方文档:https://go.dev/blog/using-go-modules

示例:

go mod init project-name

go mod init example.com/project-name

go mod init github.com/you-user-name/project-name

*在运行上述命令之后,您可能需要使用 tidy 命令进行清理。

go mod tidy

在您的 Go 文件中导入包时,请使用上述的路径格式。

示例:

import (
   //像这样导入内部和外部包
   "github.com/you-user-name/project-name/package-name"

   //像正常方式导入标准库包
   "testing"
   "math/rand"
)
英文:

Use modules to manage dependencies. Official docs: https://go.dev/blog/using-go-modules

Example:

go mod init project-name

go mod init example.com/project-name

go mod init github.com/you-user-name/project-name

*You may need to use the tidy command to clean up after running one of the above commands.

go mod tidy

Use the path format from above when importing a package into your go file

Example:

import (
   // Import internal and external packages like this
   "github.com/you-user-name/project-name/package-name"

   // Import standard library packages the normal way
   "testing"
   "math/rand"
)

答案2

得分: 0

只需在VSCode中打开您的Go文件夹,而不是打开上一级的文件夹。
VSCode希望根文件夹是包含go.mod的文件夹。
还要将您的项目的根文件夹包含在GOPATH中。

英文:

Just open your Go folder in VSCode instead of opening the folder that's one above.
VSCode expects the root folder to be the one that contains go.mod.
Also include the root folder of your project in your GOPATH

huangapple
  • 本文由 发表于 2022年8月29日 06:00:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/73522577.html
匿名

发表评论

匿名网友

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

确定