github.com/avicd/go-utilx@v0.1.0/refx/as.go (about) 1 package refx 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 func AsBool(val any) bool { 9 var ret bool 10 Assign(&ret, val) 11 return ret 12 } 13 14 func AsInt(val any) int { 15 var ret int 16 Assign(&ret, val) 17 return ret 18 } 19 20 func AsInt8(val any) int8 { 21 var ret int8 22 Assign(&ret, val) 23 return ret 24 } 25 26 func AsInt16(val any) int16 { 27 var ret int16 28 Assign(&ret, val) 29 return ret 30 } 31 32 func AsInt32(val any) int32 { 33 var ret int32 34 Assign(&ret, val) 35 return ret 36 } 37 38 func AsInt64(val any) int64 { 39 var ret int64 40 Assign(&ret, val) 41 return ret 42 } 43 44 func AsUint(val any) uint { 45 var ret uint 46 Assign(&ret, val) 47 return ret 48 } 49 50 func AsUint8(val any) uint8 { 51 var ret uint8 52 Assign(&ret, val) 53 return ret 54 } 55 56 func AsUint16(val any) uint16 { 57 var ret uint16 58 Assign(&ret, val) 59 return ret 60 } 61 62 func AsUint32(val any) uint32 { 63 var ret uint32 64 Assign(&ret, val) 65 return ret 66 } 67 68 func AsUint64(val any) uint64 { 69 var ret uint64 70 Assign(&ret, val) 71 return ret 72 } 73 74 func AsFloat32(val any) float32 { 75 var ret float32 76 Assign(&ret, val) 77 return ret 78 } 79 80 func AsFloat64(val any) float64 { 81 var ret float64 82 Assign(&ret, val) 83 return ret 84 } 85 86 func AsString(val any) string { 87 var ret string 88 Assign(&ret, val) 89 return ret 90 } 91 92 func AsListOf[T any](values ...T) []T { 93 return values 94 } 95 96 func AsList(args ...any) []any { 97 var dest []any 98 for _, arg := range args { 99 vl := ValueOf(arg) 100 if IsList(vl) { 101 for i := 0; i < vl.Len(); i++ { 102 dest = append(dest, vl.Index(i).Interface()) 103 } 104 } else { 105 dest = append(dest, vl.Interface()) 106 } 107 } 108 return dest 109 } 110 111 func AsOf(ref any, val any) reflect.Value { 112 if IsInterface(ref) { 113 return ValueOf(val) 114 } 115 dest := NewOf(ref) 116 Assign(dest.Addr(), val) 117 return dest 118 } 119 120 func AsError(val any) error { 121 if val == nil { 122 return nil 123 } 124 switch tmp := val.(type) { 125 case error: 126 return tmp 127 } 128 return fmt.Errorf("%v", val) 129 }