我正在尝试更新结构中的 map slice 。它失败: slice 保持不变。请查看游乐场:https://play.golang.org/p/FIcLgyj2FE-
任何帮助深表感谢
package main
import (
"encoding/json"
"fmt"
)
type Zoo struct {
Animals []map[string]string
}
func (zoo *Zoo) addAnimalData(el map[string]string) {
zoo.Animals = append(zoo.Animals, el)
}
func main() {
result := make(map[string]Zoo)
sfZoo := Zoo{
Animals: make([]map[string]string, 0),
}
result["San Francisco Zoo"] = sfZoo
animals := make(map[string]string)
animals["elephant"] = "Vegetarian"
animals["bear"] = "Omnivore"
sfZoo.addAnimalData(animals)
jsonified, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(jsonified))
}
最佳答案
问题是您将映射添加到sfZoo
,而不是添加到结果映射中的Zoo
实例。当您将sfZoo
添加到result
映射时,您添加了Zoo
实例的副本。将新元素添加到sfZoo
时,是将它们添加到sfZoo.Animals
而不是result["San Francisco Zoo"].Animals
中。
解决该问题的最简单方法是将结果声明为:
result := make(map[string]*Zoo)
和
result["San Francisco Zoo"] = &sfZoo
关于go - 无法更新结构中的 map slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58942901/