亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不覆蓋現有數據的情況下將鍵值添加到變量?

如何在不覆蓋現有數據的情況下將鍵值添加到變量?

Go
子衿沉夜 2022-11-23 15:50:27
我正在嘗試僅使用一個變量創建一個簡單的緩存,但我不知道如何添加到它而不每次都完全覆蓋它。這是一個片段:package mainvar store map[string][]bytetype Routes struct{}func NewRoutes() *Routes {    return &Routes{}}func (c *Routes) SetRoutes(key string, routes []byte) error {    store[key] = routes    return nil}func main() {    routes := NewRoutes()    routes.SetRoutes("key", []byte("routes"))}這將導致panic: assignment to entry in nil map. 我可以make()用來創建商店切片 - 但我不想這樣做,因為我相信我會丟失切片中已經存在的任何東西,使其變得無用。我怎么能這樣做呢?https://go.dev/play/p/NbqSbSTx5ER
查看完整描述

2 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

您正在創建一個全局變量存儲,而您很可能希望將其封裝在您的 Routes 結構中:


package main


type Routes struct{

    store map[string][]byte

}


func NewRoutes() *Routes {

    return &Routes{

        store: make(map[string][]byte),

    }

}


func (c *Routes) SetRoutes(key string, routes []byte) error {

    c.store[key] = routes


    return nil

}


func main() {

    routes := NewRoutes()


    routes.SetRoutes("key", []byte("routes"))

}

請參閱:https ://go.dev/play/p/3M4kAfya6KE 。這確保地圖的范圍限定為您的 Routes 結構并且僅初始化一次。


查看完整回答
反對 回復 2022-11-23
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

您可以檢查它是否存在nil以及make是否存在:


func (c *Routes) SetRoutes(key string, routes []byte) error {

    if store == nil {

        store = make(map[string][]byte)

    }

    store[key] = routes

    return nil

}

或者,只需在mainfunc 中進行:


func main() {

    store = make(map[string][]byte)

    routes := NewRoutes()

    routes.SetRoutes("key", []byte("routes"))

}


查看完整回答
反對 回復 2022-11-23
  • 2 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號