反射是运行时,需要在运行时解析类型信息,编译期无法优化这些操作,因此比编译时已知类型信息的直接调用效率要低。
go
package main
import (
"fmt"
"reflect"
"strings"
)
type Person struct {
Name string `json:"name" gorm:"column:name"`
Age int `json:"age" gorm:"column:age"`
}
func Parse(p interface{}) {
tp := reflect.TypeOf(p)
tv := reflect.ValueOf(p)
if tp.Kind() == reflect.Pointer {
tp = tp.Elem()
tv = tv.Elem()
}
for i := 0; i < tp.NumField(); i++ {
field := tp.Field(i)
name := field.Name
value := tv.FieldByName(name).Interface()
var column string
tag := field.Tag.Get("gorm")
parts := strings.Split(tag, ":")
if len(parts) == 2 {
column = parts[1]
}
fmt.Printf("变量名:%s 值:%v 数据库字段名:%s\n", name, value, column)
}
}
func main() {
p0 := &Person{
Name: "Jackie",
Age: 20,
}
Parse(p0)
p1 := Person{
Name: "Avalanche",
Age: 30,
}
Parse(p1)
}