我正在尝试在Go中创建一个通用方法,它将填充struct来自a 的使用数据map[string]interface{}.例如,方法签名和用法可能如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我知道这可以使用JSON作为中介来完成; 还有另一种更有效的方法吗?
在Golang中可以为JSON结构标记使用多个名称吗?
type Animation struct {
Name string `json:"name"`
Repeat int `json:"repeat"`
Speed uint `json:"speed"`
Pattern Pattern `json:"pattern",json:"frames"`
}
Run Code Online (Sandbox Code Playgroud) 我想使用自定义标签编组/解组 Golang 对象 (json)。
喜欢
type Foo struct {
Bar string `json:"test" es:"bar"`
}
data, _ := json.MarshalWithESTag(Foo{"Bar"})
log.Println(string(data)) // -> {"foo":"bar"}
Run Code Online (Sandbox Code Playgroud)
换句话说,我想在这里使用带有不同标签的encoding/json库: https: //github.com/golang/go/blob/master/src/encoding/json/encode.go#L1033
谢谢 :)