第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

在 golang 中使用私有地圖、切片的最佳實(shí)踐是什么?

在 golang 中使用私有地圖、切片的最佳實(shí)踐是什么?

Go
萬千封印 2021-10-25 20:25:41
我希望在地圖更新時(shí)收到通知,以便我可以重新計(jì)算總數(shù)。我的第一個(gè)想法是保持地圖私有,并公開一個(gè) add 方法。這是有效的,但隨后我需要能夠允許讀取和迭代地圖(基本上,只讀或地圖的副本)。我發(fā)現(xiàn)發(fā)送了地圖的副本,但底層數(shù)組或數(shù)據(jù)是相同的,并且實(shí)際上由使用“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貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊

返回地圖的副本(不是地圖值而是所有內(nèi)容)可能會(huì)更好。切片也是如此。


請(qǐng)注意,地圖和切片是描述符。如果您返回一個(gè)映射值,它將引用相同的底層數(shù)據(jù)結(jié)構(gòu)。有關(guān)詳細(xì)信息,請(qǐng)參閱博客文章Go maps in action。


創(chuàng)建一個(gè)新地圖,復(fù)制元素并返回新地圖。這樣你就不用擔(dān)心誰修改了。


制作地圖的克?。?/p>


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

}

測(cè)試Clone()函數(shù)(在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)

}


查看完整回答
反對(duì) 回復(fù) 2021-10-25
  • 3 回答
  • 0 關(guān)注
  • 186 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)