github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/ptr/conv.go (about) 1 package ptr 2 3 import ( 4 "reflect" 5 "strconv" 6 7 "github.com/jxskiss/gopkg/v2/internal/constraints" 8 ) 9 10 // IntToStringp converts Integer x to a string pointer. 11 func IntToStringp[T constraints.Integer](x T) *string { 12 rv := reflect.ValueOf(x) 13 switch rv.Kind() { 14 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 15 s := strconv.FormatInt(rv.Int(), 10) 16 return &s 17 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: 18 s := strconv.FormatUint(rv.Uint(), 10) 19 return &s 20 } 21 panic("bug: unreachable code") 22 } 23 24 // IntpToStringp converts x to a string pointer. 25 // It returns nil if x is nil. 26 func IntpToStringp[T constraints.Integer](x *T) *string { 27 if x == nil { 28 return nil 29 } 30 rv := reflect.ValueOf(*x) 31 switch rv.Kind() { 32 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 33 s := strconv.FormatInt(rv.Int(), 10) 34 return &s 35 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: 36 s := strconv.FormatUint(rv.Uint(), 10) 37 return &s 38 } 39 panic("bug: unreachable code") 40 } 41 42 // IntpToString converts x to a string. 43 // It returns an empty string if x is nil. 44 func IntpToString[T constraints.Integer](x *T) string { 45 if x == nil { 46 return "" 47 } 48 rv := reflect.ValueOf(*x) 49 switch rv.Kind() { 50 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 51 s := strconv.FormatInt(rv.Int(), 10) 52 return s 53 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr: 54 s := strconv.FormatUint(rv.Uint(), 10) 55 return s 56 } 57 panic("bug: unreachable code") 58 }