Aller au contenu

Public Mutable Field (ARCH5186)

Ce contenu n’est pas encore disponible dans votre langue.

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.

type Account struct {
Balance int // anyone can write freely
}
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.