github.com/jxskiss/gopkg@v0.17.3/easy/utils.go (about) 1 package easy 2 3 import ( 4 "github.com/jxskiss/gopkg/reflectx" 5 "reflect" 6 ) 7 8 // SetDefault checks whether dst points to a zero value, if yes, it sets 9 // the first non-zero value to dst. 10 // dst must be a pointer to same type as value, else it panics. 11 func SetDefault(dst interface{}, value ...interface{}) { 12 dstVal := reflect.ValueOf(dst) 13 if dstVal.Kind() != reflect.Ptr || !reflect.Indirect(dstVal).IsValid() { 14 panic("SetDefault: dst must be a non-nil pointer") 15 } 16 if reflect.Indirect(dstVal).IsZero() { 17 kind := dstVal.Elem().Kind() 18 for _, x := range value { 19 xval := reflect.ValueOf(x) 20 if !xval.IsZero() { 21 switch kind { 22 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 23 dstVal.Elem().SetInt(reflectx.ReflectInt(xval)) 24 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 25 dstVal.Elem().SetUint(uint64(reflectx.ReflectInt(xval))) 26 case reflect.Float32, reflect.Float64: 27 dstVal.Elem().SetFloat(xval.Float()) 28 default: 29 dstVal.Elem().Set(xval) 30 } 31 break 32 } 33 } 34 } 35 }