我想在{"foo2": "bar2"}
中data
下方sample
的结构fmt.Println(s)
中向main()
添加数据{。}}。
type sample struct {
data interface{}
}
func (s *sample) func1() {
obj := map[string]interface{}{}
obj["foo1"] = "bar1"
s.data = obj
}
func main() {
s := &sample{}
s.func1()
fmt.Println(s)
// Above here is fixed as a condition of this question.
// Here, I want to add {"foo2": "bar2"} to s.data
}
我在下面尝试过。
s.data["foo2"] = "bar2"
发生错误。它是type interface {} does not support indexing
。
obj := map[string]interface{}{}
t, _ := json.Marshal(s.data)
json.Unmarshal(t, &obj)
obj["foo2"] = "bar2"
fmt.Println(obj)
没有错误。可以添加{"foo2": "bar2"}
。
这第二次测试是有效还是一般方法?如果有如何直接添加数据或其他方法,请你教我。 非常感谢您的参与。对于我不成熟的问题,我很抱歉。
答案 0 :(得分:0)
如果您将结构的定义更改为:
type sample struct {
data map[string]interface{}
}
它应该有用。
为什么?因为您将数据定义为interface{}
。但是你这不是一个地图它是一个空的界面。为什么它不是地图?因为它也可以是int,string或其他结构。因此,您不能像其他类型一样使用该类型。
在您的示例中,您始终将data
用作地图,因此解决方案是将数据定义为类型map[string]interface{}
答案 1 :(得分:0)
我不知道你想要一个空接口类型而不是map [string] interface {}类型的原因,但是可以这样做。
type sample struct {
data interface{}
}
func (s *sample) func1() {
obj := map[string]interface{}{}
obj["foo1"] = "bar1"
s.data = obj
}
func (s *sample) addField(key, value string) {
v, _ := s.data.(map[string]interface{})
v[key] = value
s.data = v
}
func main() {
s := &sample{}
s.func1()
fmt.Println(s)
s.addField("foo2", "bar2")
fmt.Println(s)
}
每次要添加值时,都必须将接口转换为map [string] interface {}。这也可以用来检索一个值,我相信你可以使用我提供的方法添加另一个方法。
我建议不要这样做。要么你总是有一个map [string] interface {},所以你应该把它作为数据类型,或者你必须要小心,因为不能保证你有一个map [string] interface {}所以你必须相应地处理这个问题。