-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.go
44 lines (40 loc) · 1.22 KB
/
convert.go
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
/*
* 纸喵软件
* Copyright (c) 2017~2020 http://zhimiao.org All rights reserved.
* Author: 倒霉狐狸 <mail@xiaoliu.org>
* Date: 2020/3/3 下午4:26
*/
package gutils
import (
"reflect"
)
// SuperConvert 使用反射,转换结构体 仅支持单层级
func SuperConvert(fromStruct interface{}, toStruct interface{}) {
fromStructMap := structToMap(fromStruct)
toStructV := reflect.ValueOf(toStruct).Elem()
toStructT := reflect.TypeOf(toStruct).Elem()
for i := 0; i < toStructV.NumField(); i++ {
fieldName := toStructT.Field(i).Name
if sourceVal, ok := fromStructMap[fieldName]; ok {
if !sourceVal.IsValid() {
continue
}
toStructVal := toStructV.Field(i)
sourceName := sourceVal.Type().PkgPath() + sourceVal.Type().Name()
toName := toStructVal.Type().PkgPath() + toStructVal.Type().Name()
if toStructVal.CanSet() && sourceName == toName {
toStructVal.Set(sourceVal)
}
}
}
}
func structToMap(structName interface{}) map[string]reflect.Value {
t := reflect.TypeOf(structName).Elem()
v := reflect.ValueOf(structName).Elem()
fieldNum := t.NumField()
resMap := make(map[string]reflect.Value, fieldNum)
for i := 0; i < fieldNum; i++ {
resMap[t.Field(i).Name] = v.Field(i)
}
return resMap
}