I’ve got a linter for that (v0.0.1)
Gophercon EU, 29. June 2023
Paula Babbicola
Ecosia
@pbabbicola
Linting
SECTION ONE
(it’s currently 44)
What is a linter?
01. Introduction
Why lint?
01. Introduction
Why golangci-lint?
01. Introduction
Helpful error message
Errors in all go linters are very explicit.
01. Introduction
❯ golangci-lint run .
main.go:11:2: exitAfterDefer: log.Fatal will exit, and `defer fmt.Println("test!")` will not run (gocritic)
log.Fatal(1)
^
Pretty VSCode integration
It is, however, not as pretty as my dog.
01. Introduction
Common error examples
SECTION TWO
Defers after exits
This happens when you defer in the same block as you exit.
02. Common errors
func main() {
defer fmt.Println("test!")
…
if err != nil {
log.Fatal(1)
}
}
Don’t lie, you’ve done this too
gocritic: exitAfterDefer
Range variables in loops
Range variables in a loop are reused at each iteration. Assuming proper concurrency handling, listOfNumbers will end up containing {1, 2, 3, 4, 10}.
02. Common errors
listOfNumbers := []int{1, 2, 3, 4, 5}
for i := range listOfNumbers {
go func() {
listOfNumbers[i]++
}()
}
That’s illegal
range-val-in-closure
Memory alignment
This struct could be of size 24 bytes but is currently of 32 bytes.
02. Common errors
type someStruct struct {
Value1 float64
Value2 bool
Value3 float64
Value4 bool
}
maligned
Preallocating a slice
Since we are ranging through the origin slice, we can predict the destination slice will be the same size.
02. Common errors
func someFunction(origin []int) []int {
var destination []int
for _, element := range origin {
destination = append(destination, element*2)
}
return destination
}
prealloc
Returning an interface
Accept Interfaces, Return Structs
02. Common errors
func someFunction() SomeInterface {
return &SomeStruct{}
}
ireturn
More errors that it can flag
02. Common errors
type someStruct struct {
ctx context.Context
ConfusingFields string
confusingFields string
}
Context within a struct (containedctx)
Names that differ only by capitalisation (revive)
More errors that it can flag
02. Common errors
func someFunction(number int, ctx context.Context) []int {
var someSlice []int
if number > 0 {
for i, _ := range someSlice {
someSlice[i]++
}
return someSlice
} else {
return someSlice
}
}
Context is not first parameter (revive)
Unused parameter (unparam)
This for can be written in a simpler way (gofmt)
{
}
This else is unneeded (revive)
Other things it can detect
02. Common errors
Even more things it can detect
02. Common errors
Thank you!
CLOSING
For a complete list of linters: https://golangci-lint.run/