Dong.Ge

左手代码 右手江湖

reflect 再应用

东哥's Avatar 2020-03-06

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main

import (
"fmt"
"reflect"
)

type ChangeMobileQuestion struct {
Id int64 `orm:"pk;"`
Title string
Classify string

Option1 string `orm:"column(option_1)"`
OptionValue1 string `orm:"column(option_value_1)"`
Option2 string `orm:"column(option_2)"`
OptionValue2 string `orm:"column(option_value_2)"`
Option3 string `orm:"column(option_3)"`
OptionValue3 string `orm:"column(option_value_3)"`
Option4 string `orm:"column(option_4)"`
OptionValue4 string `orm:"column(option_value_4)"`
Option5 string `orm:"column(option_5)"`
OptionValue5 string `orm:"column(option_value_5)"`
}

func main() {
mapOk := map[string]int{
"Option1": 1,
"Option2": 2,
"Option3": 3,
}
wcd := ChangeMobileQuestion{
Option1: "a-1",
Option2: "b-2",
Option3: "c-3",
}

val := reflect.ValueOf(&wcd).Elem()
typ := reflect.TypeOf(&wcd).Elem()

for i := 0; i < val.NumField(); i = i + 1 {
ft := typ.Field(i)
fv := val.Field(i)
vvv, ok := mapOk[ft.Name]
if ok {
switch fv.Kind() {
case reflect.String:
fmt.Println("answerId", vvv, " answerDesc", fv.String())
case reflect.Int:
fmt.Println("answerId", vvv, " answerDesc", fv.Int())
}
}
}
}

本文最后更新于 天前,文中所描述的信息可能已发生改变