-
Notifications
You must be signed in to change notification settings - Fork 1
/
different_kind.go
103 lines (81 loc) · 2.06 KB
/
different_kind.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package goentities
import (
"reflect"
)
var allowedInts = map[reflect.Kind]struct{}{
reflect.Int: {},
reflect.Int8: {},
reflect.Int16: {},
reflect.Int32: {},
reflect.Int64: {},
}
var allowedFloats = map[reflect.Kind]struct{}{
reflect.Float32: {},
reflect.Float64: {},
}
var allowedUints = map[reflect.Kind]struct{}{
reflect.Uint: {},
reflect.Uint8: {},
reflect.Uint16: {},
reflect.Uint32: {},
reflect.Uint64: {},
}
func castDifferentKind(field, value *reflect.Value) {
if field.Type().Kind() == reflect.Ptr {
pointerFieldCasting(field, value)
return
}
if value.Type().Kind() == reflect.Ptr {
pointerValueCasting(field, value)
return
}
if field.Type().Kind() == value.Type().Kind() {
castField(field, value)
return
}
if _, ok := allowedInts[field.Type().Kind()]; ok {
intCasting(field, value)
return
}
if _, ok := allowedFloats[field.Type().Kind()]; ok {
floatCasting(field, value)
return
}
if _, ok := allowedUints[field.Type().Kind()]; ok {
uintCasting(field, value)
return
}
if field.Type().Kind() == reflect.Interface {
field.Set(*value)
return
}
// here i think we can panic because the person is
// trying to cast very different kind of fields all together
}
func intCasting(field, value *reflect.Value) {
if _, ok := allowedInts[field.Type().Kind()]; !ok {
panic("Can not cast non int type to int")
}
if _, ok := allowedInts[value.Type().Kind()]; !ok {
panic("Can not cast non int type to int")
}
field.SetInt(value.Int())
}
func uintCasting(field, value *reflect.Value) {
if _, ok := allowedUints[field.Type().Kind()]; !ok {
panic("Can not cast non float type to float")
}
if _, ok := allowedUints[field.Type().Kind()]; !ok {
panic("Can not cast non float type to float")
}
field.SetUint(value.Uint())
}
func floatCasting(field, value *reflect.Value) {
if _, ok := allowedFloats[field.Type().Kind()]; !ok {
panic("Can not cast non float type to float")
}
if _, ok := allowedFloats[field.Type().Kind()]; !ok {
panic("Can not cast non float type to float")
}
field.SetFloat(value.Float())
}