Skip to content

Go Linter 🧐 that checks that embedded fields 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.

License

Notifications You must be signed in to change notification settings

manuelarte/embeddedstructfieldcheck

Repository files navigation

EmbeddedStructFieldCheck

Go Go Report Card version

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
}

⬇️ Getting Started

As a golangci-lint linter

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

Standalone application

Install EmbeddedStructFieldCheck by running:

go install github.com/manuelarte/embeddedstructfieldcheck@latest

And then use it as:

embeddedstructfieldcheck [-forbid-mutex] [--fix]
  • forbid-mutex: true|false (default false) Checks that sync.Mutex and sync.RWMutex are not used as embedded fields.
  • fix: true|false (default false) Fix the case when there is no space between the embedded fields and the regular fields.

Why not using sync.Mutex as embedded field

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()

Resources

About

Go Linter 🧐 that checks that embedded fields 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.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •