Linter that checks that embedded types should be at the top of the field list of a struct. And there must be an empty line separating embedded fields from regular fields.
❌ Bad | ✅ Good |
---|---|
type Client struct {
version int
http.Client
} |
type Client struct {
http.Client
version int
} |
Enable the linter in your golangci-lint configuration file, e.g:
linters:
enable:
- embeddedstructfieldcheck
...
settings:
embeddedstructfieldcheck:
# Checks that sync.Mutex and sync.RWMutex are not used as embedded fields.
# Default: false
forbid-mutex: true
Install EmbeddedStructFieldCheck by running:
go install github.com/manuelarte/embeddedstructfieldcheck@latest
And then use it as:
embeddedstructfieldcheck [-forbid-mutex] [--fix]
forbid-mutex
:true|false
(defaultfalse
) Checks thatsync.Mutex
andsync.RWMutex
are not used as embedded fields.fix
:true|false
(defaultfalse
) Fix the case when there is no space between the embedded fields and the regular fields.
You are granting access to your internal synchronization methods out of your struct.
This should not be delegated out to the callers. It's a source of bugs.
As an example:
❌ Bad | ✅ Good |
---|---|
type ViewCount struct {
sync.Mutex
N int
}
v := ViewCount{}
v.Lock()
v.N++
v.Unlock() |
type ViewCount struct {
mu sync.Mutex
n int
}
func (v *ViewCount) Increment() {
v.mu.Lock()
defer v.mu.Unlock()
v.n++
}
v := ViewCount{}
v.Increment() |