【发布时间】:2017-11-21 04:06:28
【问题描述】:
type Foo struct {
M map[string]interface{} `json:"m"`
}
type Bar struct {
I int `json:"i"`
}
type Bar2 struct {
S string `json:"s"`
}
func do() {
concreteFoo1 := Foo {
M: make(map[string]Bar),
}
json.Unmarshal([]byte(`{"m": {"a": { "i": 1 }}}`), &concreteFoo1)
concreteFoo2 := Foo {
M: make(map[string]Bar2),
}
json.Unmarshal([]byte(`{"m": {"a": { "s": "hello" }}}`), &concreteFoo2)
}
编译失败:
不能使用 make(map[string]Bar) (type map[string]Bar) 作为类型 map[string]interface {} in field value
不能使用 make(map[string]Bar2) (type map[string]Bar2) 作为类型 map[string]interface {} in field value
如何编译并支持 Foo 的两种变体?
【问题讨论】:
-
"我怎样才能让它编译并支持 Foo 的两种变体?"你不能。您必须决定 Foo.M. 的类型。