因为在开发过程当中遇到类型转换问题,好比在web中某个参数是以string存在的,这个时候须要转换成其余类型,这里官方的strconv包里有这几种转换方法。web
实现函数
有两个函数能够实现类型的互转(以int转string为例)
1. FormatInt (int64,base int)string
2. Itoa(int)string
打开strconv包能够发现Itoa的实现方式以下:.net
// Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string {
return FormatInt(int64(i), 10)
}orm
也就是说itoa实际上是更便捷版的FormatInt,以此类推,其余的实现也相似的。blog
示例开发
int 和string 互转
//int 转化为string
s := strconv.Itoa(i)
s := strconv.FormatInt(int64(i), 10) //强制转化为int64后使用FormatInt字符串
//string 转为int
i, err := strconv.Atoi(s) string
int64 和 string 互转
//int64 转 string,第二个参数为基数
s := strconv.FormatInt(i64, 10)
// string 转换为 int64
//第二参数为基数,后面为位数,能够转换为int32,int64等
i64, err := strconv.ParseInt(s, 10, 64) it
float 和 string 互转
// flaot 转为string 最后一位是位数设置float32或float64
s1 := strconv.FormatFloat(v, 'E', -1, 32)
//string 转 float 一样最后一位设置位数
v, err := strconv.ParseFloat(s, 32)
v, err := strconv.atof32(s)float
bool 和 string 互转
// ParseBool returns the boolean value represented by the string.
// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
// Any other value returns an error.
func ParseBool(str string) (bool, error) {
switch str {
case "1", "t", "T", "true", "TRUE", "True":
return true, nil
case "0", "f", "F", "false", "FALSE", "False":
return false, nil
}
return false, syntaxError("ParseBool", str)
}
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
if b {
return "true"
}
return "false"
}
//上面是官方实现,不难发现字符串t,true,1都是真值。
//对应转换:
b, err := strconv.ParseBool("true") // string 转bool
s := strconv.FormatBool(true) // bool 转string
interface转其余类型
有时候返回值是interface类型的,直接赋值是没法转化的。
var a interface{}
var b string
a = "123"
b = a.(string)
经过a.(string) 转化为string,经过v.(int)转化为类型。
能够经过a.(type)来判断a能够转为何类型。
原文:https://blog.csdn.net/bobodem/article/details/80182096