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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀