我试图在 Go 中创建一个通用方法,它将使用来自 map[string]interface{}
的数据填充 struct
。例如,方法签名和用法可能类似于:
func FillStruct(data map[string]interface{}, result interface{}) {
...
}
type MyStruct struct {
Name string
Age int64
}
myData := make(map[string]interface{})
myData["Name"] = "Tony"
myData["Age"] = 23
result := &MyStruct{}
FillStruct(myData, result)
// result now has Name set to "Tony" and Age set to 23
我知道这可以通过使用 JSON 作为中介来实现; 是否有其他更有效的方法来实现这一点?