utils.go
1.3 KB
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
package utils
import (
"errors"
"reflect"
)
// 此函数将指定的结构体成员值更新到结构体中
func SetStructValueByType(s interface{}, columnType string, columnValue interface{}) error {
columnValueV := reflect.ValueOf(columnValue)
var setValue reflect.Value
var flag = false
v := reflect.ValueOf(s)
for i, n := 0, v.Elem().NumField(); i < n; i++ {
if v.Elem().Type().Field(i).Name == columnType {
setValue = v.Elem().Field(i)
flag = true
break
}
}
if !flag {
return errors.New("struct is not type:")
} else if !setValue.CanSet() {
return errors.New("setValue.CanSet is false")
} else if setValue.Kind() != columnValueV.Kind() {
return errors.New("struct field and value of type is error")
}
switch columnValueV.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
setValue.SetInt(int64(columnValueV.Int()))
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
setValue.SetUint(uint64(columnValueV.Uint()))
case reflect.Float32, reflect.Float64:
setValue.SetFloat(float64(columnValueV.Float()))
case reflect.String:
setValue.SetString(columnValueV.String())
case reflect.Struct:
setValue.Set(columnValueV)
default:
return errors.New("columnValue err for:" + columnType)
}
return nil
}