donk68254 2015-08-05 15:12
浏览 34
已采纳

在golang中使用私人地图,切片的最佳做法是什么?

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?

  • 写回答

4条回答 默认 最新

  • douaoren4402 2015-08-05 15:17
    关注

    Then you could have private data and a public iterator that returns a copy of the next key/value pair upon each call, no ?

    Iterators are less present in Go than in languages that don't have built-in constructs married to particular data-structures. Nevertheless they're as easy to make as anywhere else, and pretty much as easy to use, save for the fact that there's no language syntax to range an iterator. For example, bufio.Scanner is just an iterator with a bit of convenience cruft grafted on...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面