-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlisttypes.go
More file actions
66 lines (55 loc) · 1.35 KB
/
listtypes.go
File metadata and controls
66 lines (55 loc) · 1.35 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package myflags
import (
"fmt"
"reflect"
"strconv"
)
// these are needed to support slice/array of the types
func init() {
Register[string](new(strType))
Register[float32](&floatType{len: 32})
Register[float64](&floatType{len: 64})
Register[bool](new(boolType))
}
type strType string
func (s *strType) ToStr(in any, tag reflect.StructTag) string {
if reflect.ValueOf(in).Kind() == reflect.Pointer {
return *(in.(*string))
}
return in.(string)
}
func (s *strType) FromStr(input string, tag reflect.StructTag) (any, error) {
return input, nil
}
type boolType bool
func (b *boolType) ToStr(in any, tag reflect.StructTag) string {
if reflect.ValueOf(in).Kind() == reflect.Pointer {
return fmt.Sprint(*(in.(*bool)))
}
return fmt.Sprint(in)
}
func (b *boolType) FromStr(input string, tag reflect.StructTag) (any, error) {
return strconv.ParseBool(input)
}
type floatType struct {
len int
}
func (f *floatType) ToStr(in any, tag reflect.StructTag) string {
//if in is a pointer, convert it to the value
val := reflect.ValueOf(in)
if val.Kind() == reflect.Pointer {
val = val.Elem()
}
return fmt.Sprint(val.Interface())
}
func (f *floatType) FromStr(s string, tag reflect.StructTag) (any, error) {
f64, err := strconv.ParseFloat(s, f.len)
if err != nil {
return 0, nil
}
switch f.len {
case 32:
return float32(f64), nil
}
return f64, nil
}