2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為你必須稍微改變一下實(shí)現(xiàn)
var p1 Person
mapstructure.Decode(p_map, &p1)
b := Bundle{
p1,
}
print(b.Struct.(Person).Name) // John will appear
我正在嘗試上面的代碼,但導(dǎo)致 empty Person。也許Decode函數(shù)不能改變的實(shí)際值b.Struct(我不確定確切的原因,這只是我的意見(jiàn)),但如果我Person先解碼為結(jié)構(gòu)然后分配給Bundle那個(gè)作品。
更新:通過(guò)一些研究,我發(fā)現(xiàn)了問(wèn)題所在。您必須使用指針而不是結(jié)構(gòu)。這里是更新的代碼
package main
import (
"github.com/mitchellh/mapstructure"
)
type Person struct {
Name string
}
type Bundle struct {
Name string
Struct interface{}
}
func main() {
p_map := map[string]string{
"Name": "John",
}
p := &Person{}
mapstructure.Decode(p_map, &p)
print(p.Name) // shows name John
b := Bundle{
"person",
&Person{},
}
mapstructure.Decode(p_map, &b.Struct)
print(b.Struct.(*Person).Name) // Does not show any name. Blank
}

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
將 Bundle 中的 Struct 字段類型從 interface{} 更改為 Person 后,它對(duì)我有用。
type Bundle struct {
Struct Person
}
print(b.Struct.Name)
- 2 回答
- 0 關(guān)注
- 167 瀏覽
添加回答
舉報(bào)