为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 中使用私有地图、切片的最佳实践是什么?

在 golang 中使用私有地图、切片的最佳实践是什么?

Go
万千封印 2021-10-25 20:25:41
我希望在地图更新时收到通知,以便我可以重新计算总数。我的第一个想法是保持地图私有,并公开一个 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 中有推荐的方法吗?
查看完整描述

3 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

返回地图的副本(不是地图值而是所有内容)可能会更好。切片也是如此。


请注意,地图和切片是描述符。如果您返回一个映射值,它将引用相同的底层数据结构。有关详细信息,请参阅博客文章Go maps in action。


创建一个新地图,复制元素并返回新地图。这样你就不用担心谁修改了。


制作地图的克隆:


func Clone(m map[string]Money) map[string]Money {

    m2 := make(map[string]Money, len(m))


    for k, v := range m {

        m2[k] = v

    }

    return m2

}

测试Clone()函数(在Go Playground上试试):


m := map[string]Money{"one": 1, "two": 2}

m2 := Clone(m)

m2["one"] = 11

m2["three"] = 3

fmt.Println(m) // Prints "map[one:1 two:2]", not effected by changes to m2

所以你的GetMailbox()方法:


func (a Account) GetMailbox() map[string]Money{

    return Clone(a.mailbox)

}


查看完整回答
反对 回复 2021-10-25
  • 3 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信