2 回答

TA貢獻1780條經驗 獲得超5個贊
我認為你必須稍微改變一下實現
var p1 Person
mapstructure.Decode(p_map, &p1)
b := Bundle{
p1,
}
print(b.Struct.(Person).Name) // John will appear
我正在嘗試上面的代碼,但導致 empty Person。也許Decode函數不能改變的實際值b.Struct(我不確定確切的原因,這只是我的意見),但如果我Person先解碼為結構然后分配給Bundle那個作品。
更新:通過一些研究,我發現了問題所在。您必須使用指針而不是結構。這里是更新的代碼
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貢獻1827條經驗 獲得超8個贊
將 Bundle 中的 Struct 字段類型從 interface{} 更改為 Person 后,它對我有用。
type Bundle struct {
Struct Person
}
print(b.Struct.Name)
- 2 回答
- 0 關注
- 154 瀏覽
添加回答
舉報