Search code examples
govisual-studio-codegolint

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


I tried this code in Go:

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

And VS Code reports the following problem:

exported type Agent should have comment or be unexported


The warning is kind of annoying. So I have the following questions:

  • How to get rid of it?
  • What comment should I put?
  • Is there any default comment template for this?

It asks me to put a comment but it does not offer me to add one by default.


Solution

  • Just add a comment above it, starting with the name of your type (or function, method etc.) like this:

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

    This linter error is caused by your Agent type being exported, even if its attributes are not. To not export your type, define it in lowercase like such:

    type agent struct {
       name string
       categoryId int
    }
    

    The reason why your linter complains about this is that godoc uses those comments to automatically generate documentation for your projects. You can find many examples of such documented Go projects at pkg.go.dev.

    If you upload one of your Go projects to GitHub for example, pkg.go.dev will automatically generate a documentation for you using those comments. You can even add runnable code examples and many other things, as shown on go-doc tricks.