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

我希望在地图更新时收到通知,以便我可以重新计算总数。我的第一个想法是保持地图私有,并公开一个 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 中有推荐的方法吗?


万千封印
浏览 161回答 3
3回答

隔江千里

返回地图的副本(不是地图值而是所有内容)可能会更好。切片也是如此。请注意,地图和切片是描述符。如果您返回一个映射值,它将引用相同的底层数据结构。有关详细信息,请参阅博客文章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"] = 11m2["three"] = 3fmt.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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go