我有一个 JSON,需要对其进行一些处理。它使用了我需要以某种方式引用的切片,以便在函数结束时修改 Room-struct。如何以引用类型的方式同时使用此结构?
http://play.golang.org/p/wRhd1sDqtb
type Window struct {
Height int64 `json:"Height"`
Width int64 `json:"Width"`
}
type Room struct {
Windows []Window `json:"Windows"`
}
func main() {
js := []byte(`{"Windows":[{"Height":10,"Width":20},{"Height":10,"Width":20}]}`)
fmt.Printf("Should have 2 windows: %v\n", string(js))
var room Room
_ = json.Unmarshal(js, &room)
var wg sync.WaitGroup
// Add many windows to room
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
addWindow(room.Windows)
}()
}
wg.Wait()
js, _ = json.Marshal(room)
fmt.Printf("Sould have 12 windows: %v\n", string(js))
}
func addWindow(windows []Window) {
window := Window{1, 1}
// Do some expensive calculations
fmt.Printf("Adding %v to %v\n", window, windows)
windows = append(windows, window)
}