MCPcopy
hub / github.com/spf13/cast / toNumber

Function toNumber

number.go:91–136  ·  view source on GitHub ↗

toNumber's semantics differ from other "to" functions. It returns false as the second parameter if the conversion fails. This is to signal other callers that they should proceed with their own conversions.

(i any)

Source from the content-addressed store, hash-verified

89// It returns false as the second parameter if the conversion fails.
90// This is to signal other callers that they should proceed with their own conversions.
91func toNumber[T Number](i any) (T, bool) {
92 i, _ = indirect(i)
93
94 switch s := i.(type) {
95 case T:
96 return s, true
97 case int:
98 return T(s), true
99 case int8:
100 return T(s), true
101 case int16:
102 return T(s), true
103 case int32:
104 return T(s), true
105 case int64:
106 return T(s), true
107 case uint:
108 return T(s), true
109 case uint8:
110 return T(s), true
111 case uint16:
112 return T(s), true
113 case uint32:
114 return T(s), true
115 case uint64:
116 return T(s), true
117 case float32:
118 return T(s), true
119 case float64:
120 return T(s), true
121 case bool:
122 if s {
123 return 1, true
124 }
125
126 return 0, true
127 case nil:
128 return 0, true
129 case time.Weekday:
130 return T(s), true
131 case time.Month:
132 return T(s), true
133 }
134
135 return 0, false
136}
137
138func toNumberE[T Number](i any, parseFn func(string) (T, error)) (T, error) {
139 n, ok := toNumber[T](i)

Callers

nothing calls this directly

Calls 1

indirectFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…