Golang类型转换

golang是强类型语言,在应用过程中类型转换基本都会用到。下面整理一下常用的类型转换,会持续更新。

bytes 、string转换

//类型转换  string to bytes
func str2bytes(s string) []byte {
    x := (*[2]uintptr)(unsafe.Pointer(&s))
    h := [3]uintptr{x[0], x[1], x[1]}
    return *(*[]byte)(unsafe.Pointer(&h))
}

//类型转换  bytes to string
func bytes2str(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

interface转为string

//interface转为string
func interface2string(inter interface{}) string {
    tempStr := ""
    switch inter.(type) {
    case string:
        tempStr = inter.(string)
        break
    case float64:
        tempStr = strconv.FormatFloat(inter.(float64), 'f', -1, 64)
        break
    case int64:
        tempStr = strconv.FormatInt(inter.(int64), 10)
        break
    case int:
        tempStr = strconv.Itoa(inter.(int))
        break
    }
    return tempStr
}

最新更新日期20161219

func ToStr(value interface{}, args ...int) (s string) {
    switch v := value.(type) {
    case bool:
        s = strconv.FormatBool(v)
    case float32:
        s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
    case float64:
        s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
    case int:
        s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
    case int8:
        s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
    case int16:
        s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
    case int32:
        s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
    case int64:
        s = strconv.FormatInt(v, argInt(args).Get(0, 10))
    case uint:
        s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
    case uint8:
        s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
    case uint16:
        s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
    case uint32:
        s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
    case uint64:
        s = strconv.FormatUint(v, argInt(args).Get(0, 10))
    case string:
        s = v
    case []byte:
        s = string(v)
    default:
        s = fmt.Sprintf("%v", v)
    }
    return s
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值