Enforcing Field Names in Go
The problem
Sometimes, you want a struct field in Go to clearly convey its meaning through its value. However, you also want to enforce that the caller explicitly provides the field names to ensure the struct remains clear and understandable.
// Bad
User{"Foo", 16, "foo@bar.com"}
// Good
User{Name: "Foo", Age: 16, Email: "foo@bar.com"}
This post introduces a technique to enforce the use of field names when initializing structs
.
This technique has been discussed and well-documented in a Github issue (https://github.com/golang/go/issues/2794) and has found its way into various Go codebases.
Here's the trick in action:
type Struct struct {
A int
B string
_ struct{} // The trick
}
With this struct definition, any usage of Struct{1, "2"}
will result in a compile error, prompting developers to specify field names.
Compile Error:
./prog.go:4:16: too few values in Struct literal
The _ struct{}
field serves as a clever reminder for the developer to be more explicit about their intentions when creating struct literals.