Go Linter to check struct's field initialization order.
To install it, run:
go install github.com/manuelarte/structinit@latestAnd then use it with:
structinit [--fix] ./...- fix:
true|false(defaultfalse) Fix the field instantiation order.
You can integrate this linter with golangci-lint by using the module plugin.
Example of a custom-gcl.yml file that includes this linter:
version: v2.12.2
plugins:
- module: "github.com/manuelarte/structinit"
import: "github.com/manuelarte/structinit/plugin"
version: latestBy marking a struct with //go:structinit, that indicates that whenever you initialize that struct, the fields
need to be initialized in the same order as they are declared in the struct.
//go:structinit
type MyStruct struct {
Field1 string
Field2 int
func NewMyStruct() *MyStruct {
return &MyStruct{
Field1: "value1",
Field2: 42,
}
}
func OtherMyStruct() *MyStruct {
return &MyStruct{ // Linter will complain about this, since it's expecting Field1 to be initialized first.
Field2: 42,
Field1: "value1",
}
}There are several reasons why it is not "easy" to lint every instantiation of a struct. When instantiating a struct not using "static" values, there could be some side effects. Check example.go.