在 main.go 文件夹中 "package main" 标记为红色时出错

error with "package main" flagging red in the main.go folder

我写了一个 main.go 程序并在代码的开头声明了包,但它标记为红色,如下所示:

当我将鼠标悬停在包裹上时,它会显示以下内容:

gopls requires a module at the root of your workspace.
You can work with multiple modules by opening each one as a workspace folder.
Improvements to this workflow will be coming soon, and you can learn more here:
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.

我需要有关如何解决此错误的帮助。非常感谢。

您需要从项目根目录的命令行中 运行 命令 go mod init。它看起来像你 运行 它来自 go-microservice/prod-api,但它应该是 运行 在你 .git 居住的同一个地方。如果 prod-api 实际上是 git 项目的根目录,那么您需要在 VSCode 而不是 go-microservice.

中打开该文件夹

我刚开始使用 golang,所以我不确定这是否对你有帮助。

这个错误出现在 VS Code 中,为了解决这个问题,我需要将一个空的 github 存储库克隆到一个新文件夹中,以便稍后添加 main.go 文件。

我能够添加、提交和推送更改。 lint 错误现在消失了。

在我的例子中,.git 文件夹位于上方,而不是在 main.go:

旁边
\my-app
  |
  |__ \backend
      |__ go.mod
      |__ main.go
  |__ \frontend
  |__ \.git

在后端文件夹中,go.mod 是用

生成的
go mod init github.com/<your-username>/my-app

似乎 GitHub 将默认分支从 master 更改为 main。如果您使用 github,请检查您是否在正确的分支中,默认情况下可能是 main

如果你将hello.go从prod-api移动到GO-MICROSERVICE的根文件夹,那么你不会有错误。

您可以通过在 gopls 设置中添加 "build.experimentalWorkspaceModule": true 来禁用此问题
This mentioned in the link appear in the error