Public Mutable Field (ARCH5186)
Esta página aún no está disponible en tu idioma.
Key go.quality.exported-mutable-field · Severity info · Category quality
Directly exported mutable fields make it impossible to enforce invariants and leak internal state. Hide the field and expose accessors.
Incorrect
Section titled “Incorrect”type Account struct { Balance int // anyone can write freely}Correct
Section titled “Correct”type Account struct { balance int}
func (a *Account) Balance() int { return a.balance }
func (a *Account) Deposit(n int) error { if n <= 0 { return errInvalidAmount } a.balance += n return nil}Make the field unexported and add accessor methods that enforce invariants.