I would like to be notified when a map is updated so that I can recalculate the Total. My first thought was to keep the map private, and expose an add method. This works, but then I needed to be able to allow the map to be read and iterated over (Basically, read only or a copy of the map). What I found was that a copy of the map is sent, but the underlying array, or data is the same and actually gets updated by anyone who uses the "getter".
type Account struct{
Name string
total Money
mailbox map[string]Money // I want to make this private but it seems impossible to give read only access - and a public Add method
}
func (a *Account) GetMailbox() map[string]Money{ //people should be able to view this map, but I need to be notified when they edit it.
return a.mailbox
}
func (a *Account) UpdateEnvelope(s string, m Money){
a.mailbox[s] = m
a.updateTotal()
}...
Is there a recommended way of doing this in Go?