Golang类型转换
2016-11-25 11:45
197 查看
golang是强类型语言,在应用过程中类型转换基本都会用到。下面整理一下常用的类型转换,会持续更新。
最新更新日期20161219
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 }
相关文章推荐
- golang 断言 + 类型转换
- Golang类型转换
- Golang 奇葩的时间包之Json与struct对象之间互相转换,JsonDate和JsonTime自定义类型如何实现json编码和解码(二)
- golang json类型不确定时的转换
- golang基础-接口、接口嵌套、类型断言、接口与结构体_接口等转换
- golang--从类型转换角度看interface
- golang 无法将Slice类型[]a 转换为 Slice[]b
- golang 文件IO 类型转换
- Golang 类型转换整理
- Golang 类型转换
- golang 数据类型的转换
- golang学习之interface与其它类型转换
- golang常用类型之间的转换
- golang 类型转换
- golang的类型转换的坑和分析
- golang: 类型转换和类型断言
- golang的interface到其他类型的数据转换
- golang语法总结(八):类型零值、类型别名、类型转换
- Go实战--golang中获取公网ip、查看内网ip、检测ip类型、校验ip区间、ip地址string和int转换、根据ip判断地区国家运营商等
- golang 类型转换