我希望在地图更新时收到通知,以便我可以重新计算总数。我的第一个想法是保持地图私有,并公开一个 add 方法。这是有效的,但随后我需要能够允许读取和迭代地图(基本上,只读或地图的副本)。我发现发送了地图的副本,但底层数组或数据是相同的,并且实际上由使用“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()
}...
在 Go 中有推荐的方法吗?
隔江千里
相关分类