Linter checks if examples are testable (have an expected output).
Author of idea is Jamie Tanna (see this issue).
Example functions without output comments are compiled but not executed by go test
, see doc.
It means that such examples are not validated. This can lead to outdated code.
That's why the linter complains on missing output.
func Example_bad() { // <- linter will complain on missing output
fmt.Println("hello")
}
func Example_good() {
fmt.Println("hello")
// Output: hello
}
The best way is to use golangci-lint.
It includes testableexamples and a lot of other great linters.
See official site.
testableexamples
is disabled by default.
To enable it, add the following to your .golangci.yml
:
linters:
enable:
testableexamples
golangci-lint run
Here is incorrect usage of //nolint
directive.
golangci-lint
understands it correctly, but godoc
will include comment to the code.
// Description
func Example_nolintIncorrect() { //nolint:testableexamples // that's why
fmt.Println("hello")
}
Here are two examples of correct usage of //nolint
directive.
godoc
will ignore comment.
//nolint:testableexamples // that's why
func Example_nolintCorrect() {
fmt.Println("hello")
}
// Description
//
//nolint:testableexamples // that's why
func Example_nolintCorrectWithDescription() {
fmt.Println("hello")
}
go install github.com/maratori/testableexamples@latest
testableexamples ./...
Standalone linter doesn't support //nolint
directive.
And there is no alternative for that, please use golangci-lint
.