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.
funcExample_bad() { // <- linter will complain on missing outputfmt.Println("hello")
}
funcExample_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:
testableexamplesgolangci-lint runHere is incorrect usage of //nolint directive.golangci-lint understands it correctly, but godoc will include comment to the code.
// DescriptionfuncExample_nolintIncorrect() { //nolint:testableexamples // that's whyfmt.Println("hello")
}Here are two examples of correct usage of //nolint directive.godoc will ignore comment.
//nolint:testableexamples // that's whyfuncExample_nolintCorrect() {
fmt.Println("hello")
}
// Description////nolint:testableexamples // that's whyfuncExample_nolintCorrectWithDescription() {
fmt.Println("hello")
}go install github.com/maratori/testableexamples@latesttestableexamples ./...Standalone linter doesn't support //nolint directive.
And there is no alternative for that, please use golangci-lint.