github.com/go-spring/spring-base@v1.1.3/cast/bool.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package cast 18 19 import ( 20 "fmt" 21 "strconv" 22 ) 23 24 func BoolPtr(s bool) *bool { return &s } 25 26 // ToBool casts an interface{} to a bool. 27 // When type is clear, it is recommended to use standard library functions. 28 func ToBool(i interface{}) bool { 29 v, _ := ToBoolE(i) 30 return v 31 } 32 33 // ToBoolE casts an interface{} to a bool. 34 // When type is clear, it is recommended to use standard library functions. 35 func ToBoolE(i interface{}) (bool, error) { 36 switch b := i.(type) { 37 case nil: 38 return false, nil 39 case int: 40 return b != 0, nil 41 case int8: 42 return b != 0, nil 43 case int16: 44 return b != 0, nil 45 case int32: 46 return b != 0, nil 47 case int64: 48 return b != 0, nil 49 case *int: 50 return *b != 0, nil 51 case *int8: 52 return *b != 0, nil 53 case *int16: 54 return *b != 0, nil 55 case *int32: 56 return *b != 0, nil 57 case *int64: 58 return *b != 0, nil 59 case uint: 60 return b != 0, nil 61 case uint8: 62 return b != 0, nil 63 case uint16: 64 return b != 0, nil 65 case uint32: 66 return b != 0, nil 67 case uint64: 68 return b != 0, nil 69 case *uint: 70 return *b != 0, nil 71 case *uint8: 72 return *b != 0, nil 73 case *uint16: 74 return *b != 0, nil 75 case *uint32: 76 return *b != 0, nil 77 case *uint64: 78 return *b != 0, nil 79 case float32: 80 return b != 0, nil 81 case float64: 82 return b != 0, nil 83 case *float32: 84 return *b != 0, nil 85 case *float64: 86 return *b != 0, nil 87 case string: 88 return strconv.ParseBool(b) 89 case *string: 90 return strconv.ParseBool(*b) 91 case bool: 92 return b, nil 93 case *bool: 94 return *b, nil 95 default: 96 return false, fmt.Errorf("unable to cast type (%T) to bool", i) 97 } 98 }