github.com/sandwich-go/boost@v1.3.29/xconv/bool.go (about) 1 package xconv 2 3 import ( 4 "github.com/sandwich-go/boost/xstrings" 5 "reflect" 6 "strings" 7 ) 8 9 // Bool [影响性能] converts `any` to bool. 10 // It returns false if `any` is: false, "", 0, "0", "false", "off", "n", "no", empty slice/map. 11 func Bool(any interface{}) bool { 12 if any == nil { 13 return false 14 } 15 switch value := any.(type) { 16 case bool: 17 return value 18 case []byte: 19 return xstrings.IsTrue(strings.ToLower(string(value))) 20 case string: 21 return xstrings.IsTrue(strings.ToLower(value)) 22 case int: 23 return value != 0 24 case int8: 25 return value != 0 26 case int16: 27 return value != 0 28 case int32: 29 return value != 0 30 case int64: 31 return value != 0 32 case uint: 33 return value != 0 34 case uint8: 35 return value != 0 36 case uint16: 37 return value != 0 38 case uint32: 39 return value != 0 40 case uint64: 41 return value != 0 42 default: 43 if f, ok := value.(iBool); ok { 44 return f.Bool() 45 } 46 rv := reflect.ValueOf(any) 47 switch rv.Kind() { 48 case reflect.Ptr: 49 return !rv.IsNil() 50 case reflect.Map: 51 fallthrough 52 case reflect.Array: 53 fallthrough 54 case reflect.Slice: 55 return rv.Len() != 0 56 case reflect.Struct: 57 return true 58 default: 59 return xstrings.IsTrue(strings.ToLower(String(any))) 60 } 61 } 62 }