3 回答

TA貢獻1811條經(jīng)驗 獲得超6個贊
代碼有幾個問題:
地圖需要使用 make 函數(shù)進行初始化。目前他們是零
map 的返回值是不可尋址的,這是因為如果 map 增長,它需要重新定位,這將導致內(nèi)存地址發(fā)生變化。因此,我們需要從映射中顯式地提取值到變量,更新它并將其分配回來。
使用指針
我已經(jīng)更新了解決方案,以顯示返回的更新值并將其分配回來和指針。
http://play.golang.org/p/lv50AONXyU
package main
import (
"fmt"
)
type Stats struct {
cnt int
category map[string]Events
}
type Events struct {
cnt int
event map[string]*Event
}
type Event struct {
value int64
}
func main() {
stats := new(Stats)
stats.cnt = 33
stats.category = make(map[string]Events)
e, f := stats.category["aa"]
if !f {
e = Events{}
}
e.cnt = 66
e.event = make(map[string]*Event)
stats.category["aa"] = e
stats.category["aa"].event["bb"] = &Event{}
stats.category["aa"].event["bb"].value = 99
fmt.Println(stats)
fmt.Println(stats.cnt, stats.category["aa"].event["bb"].value)
}

TA貢獻1836條經(jīng)驗 獲得超5個贊
添加這個作為解決問題的不同方法:
type Stats struct {
cnt int
categories map[string]*Events
}
func (s *Stats) Category(n string) (e *Events) {
if s.categories == nil {
s.categories = map[string]*Events{}
}
if e = s.categories[n]; e == nil {
e = &Events{}
s.categories[n] = e
}
return
}
type Events struct {
cnt int
events map[string]*Event
}
func (e *Events) Event(n string) (ev *Event) {
if e.events == nil {
e.events = map[string]*Event{}
}
if ev = e.events[n]; ev == nil {
ev = &Event{}
e.events[n] = ev
}
return
}
type Event struct {
value int64
}
func main() {
var stats Stats
stats.cnt = 33
stats.Category("aa").cnt = 66
stats.Category("aa").Event("bb").value = 99
fmt.Println(stats)
fmt.Println(stats.cnt, stats.Category("aa").Event("bb").value)
}

TA貢獻1827條經(jīng)驗 獲得超8個贊
你的方法有幾個問題。
你沒有初始化你的地圖。您需要先創(chuàng)建它們。
地圖返回其值的副本。所以當你拉出“aa”并修改它時,你得到了一個“aa”的副本,改變它,然后把它扔掉。您需要將其放回地圖中,或使用指針。
這是Play上的一個工作示例(非指針版本)。
請注意映射的構(gòu)造,以及在修改值時重新分配回映射。
package main
import (
"fmt"
)
type Stats struct {
cnt int
category map[string]Events
}
type Events struct {
cnt int
event map[string]Event
}
type Event struct {
value int64
}
func main() {
stats := &Stats{category: map[string]Events{}}
stats.cnt = 33
tmpCat, ok := stats.category["aa"]
if !ok {
tmpCat = Events{event: map[string]Event{}}
}
tmpCat.cnt = 66
tmpEv := tmpCat.event["bb"]
tmpEv.value = 99
tmpCat.event["bb"] = tmpEv
stats.category["aa"] = tmpCat
fmt.Println(stats.cnt, stats.category["aa"].event["bb"].value)
}
- 3 回答
- 0 關(guān)注
- 249 瀏覽
添加回答
舉報