"Exported type should have comment or be unexported" golang VS 代码

"Exported type should have comment or be unexported" golang VS Code

我在 Go 中尝试了这段代码:

type Agent struct {
    name string    // Not exported
    categoryId int // Not exported
}

VS Code 报告了以下问题

exported type Agent should have comment or be unexported


警告有点烦人。所以我有以下问题:

它让我发表评论,但默认情况下不让我添加评论。

只需在上面添加注释,以您的类型(或函数、方法等)的名称开头,如下所示:

// Agent is ...
type Agent struct {
   name string
   categoryId int
}

此 linter 错误是由于您的 Agent 类型被导出引起的,即使它的属性没有被导出。要不导出您的类型,请将其定义为小写形式:

type agent struct {
   name string
   categoryId int
}

你的 linter 抱怨这个的原因是 godoc 使用这些评论自动为你的项目生成文档。您可以在 pkg.go.dev.

找到许多此类已记录的 Go 项目示例

例如,如果您将一个 Go 项目上传到 GitHub,pkg.go.dev 将使用这些评论自动为您生成一份文档。您甚至可以添加可运行的代码示例和许多其他内容,如 go-doc tricks.

所示

此警告由官方 linter for Go source code - golint. Golint is used as the default linter by the Go extension 在 Visual Studio 代码编辑器中生成。


为什么

要理解原因为什么golint显示warning,可以参考"Effective Go" 中的“Commentary”部分(官方文档提供了编写清晰、惯用的 Go 代码的技巧)。这是相关的引用:

Every exported (capitalized) name in a program should have a doc comment.

但这确实 可以 annoying 如果您倾向于编写 自我记录 代码(即意图很明确来自 name 本身等)。


解决方案

除了已经提议的 , what you can do is start using the alternative and more advanced golangci-lint which is a Go linters aggregator. It has golint disabled by default, so this annoying warning about missing doc comments will not be triggered. Of course you can turn this warning on if you want by using the related flags(参见 --exclude strings--exclude-use-default)。

Go 扩展的描述页面中也提到了更改 linter 的可能性:


如何在 VS Code 中更改 Go 扩展的 lint 工具

要更改 VS Code 中的 lint 工具,请执行以下步骤。

1)在 Go Extension 的管理菜单中选择“Configure Extension Settings”:

2) Select 相关下拉列表中的“golangci-lint”:

3) 为了防止 VS Code 由于使用这个强大的 linter 而冻结,请添加 --fast 标志,如 "Editor Integration" 说明中所述.

为此,您需要导航到 Go Extension 配置页面(如步骤 1 中所示),打开 settings.json 文件并添加相关配置,如下面的屏幕截图所示:

注意! 这是引用自“golangci-lintFAQ:

Why running with --fast is slow on the first run?
Because the first run caches type information. All subsequent runs will be fast. Usually this options is used during development on local machine and compilation was already performed.

您只需在函数名称上方添加注释即可解决此问题。

示例如下:

//ArrayBasic1 is the function for calculating array
func ArrayBasic1() {
  x := [5]int{1: 10, 2: 20, 3: 30}
  fmt.Println("value from arraybasic1", x)
}