-
Notifications
You must be signed in to change notification settings - Fork 0
/
cast.go
68 lines (57 loc) · 1.51 KB
/
cast.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
package godf
import (
"fmt"
"reflect"
)
func AutoCast(data interface{}) any {
switch reflect.ValueOf(data).Kind() {
case reflect.Float64:
return CastFloat64(data)
case reflect.Int:
return CastInt(data)
case reflect.String:
return CastString(data)
case reflect.Slice:
sliceType := reflect.TypeOf(data).Elem()
switch sliceType.Kind() {
case reflect.Float64:
return CastArrayFloat64(data)
case reflect.Int:
return CastArrayInt(data)
case reflect.String:
return CastArrayString(data)
default:
panic(fmt.Sprintf("Datatype %s not supported yet", sliceType.Kind()))
}
default:
panic(fmt.Sprintf("Datatype %s not supported yet", reflect.TypeOf(data).Kind()))
}
}
func CastString(data interface{}) string {
return reflect.ValueOf(data).String()
}
func CastFloat64(data interface{}) float64 {
return reflect.ValueOf(data).Float()
}
func CastInt(data interface{}) int {
return int(reflect.ValueOf(data).Int())
}
func CastArrayFloat64(data interface{}) []float64 {
return reflect.ValueOf(data).Interface().([]float64)
}
func CastArrayString(data interface{}) []string {
return reflect.ValueOf(data).Interface().([]string)
}
func CastArrayInt(data interface{}) []int {
return reflect.ValueOf(data).Interface().([]int)
}
func CastHeaders(headers []string) []interface{} {
var intfHeaders []interface{}
for _, s := range headers {
intfHeaders = append(intfHeaders, interface{}(s))
}
return intfHeaders
}
func GetDatatype(data interface{}) reflect.Kind {
return reflect.TypeOf(data).Kind()
}