Dong.Ge

左手代码 右手江湖

golang struct赋值

东哥's Avatar 2019-09-18

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var data = map[string]interface{}{
"id": 1001,
"name": "apple",
"price": 16.25,
}

type Fruit struct {
ID int
Name string
Price float64
}

// 遍历struct并且自动进行赋值
func structByReflect(data map[string]interface{}, inStructPtr interface{}) {
rType := reflect.TypeOf(inStructPtr)
rVal := reflect.ValueOf(inStructPtr)
if rType.Kind() == reflect.Ptr {
// 传入的inStructPtr是指针,需要.Elem()取得指针指向的value
rType = rType.Elem()
rVal = rVal.Elem()
} else {
panic("inStructPtr must be ptr to struct")
}
// 遍历结构体
for i := 0; i < rType.NumField(); i++ {
t := rType.Field(i)
f := rVal.Field(i)
if v, ok := data[t.Name]; ok {
f.Set(reflect.ValueOf(v))
} else {
panic(t.Name + " not found")
}
}
}
func main() {
//fruit := newFruit(data)
fruit := Fruit{}
structByReflect(data, &fruit)
log.Println("fruit:", fruit)
}
本文最后更新于 天前,文中所描述的信息可能已发生改变