由于在开发过程中遇到类型转换问题,比如在web中某个参数是以string存在的,这个时候需要转换成其他类型,这里官方的strconv包里有这几种转换方法。

实现

有两个函数可以实现类型的互转(以int转string为例) 
1. FormatInt (int64,base int)string 
2. Itoa(int)string 
打开strconv包可以发现Itoa的实现方式如下:

// Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string {
    return FormatInt(int64(i), 10)
}

也就是说itoa其实是更便捷版的FormatInt,以此类推,其他的实现也类似的。

示例

int 和string 互转
//int 转化为string
s := strconv.Itoa(i) 
s := strconv.FormatInt(int64(i), 10) //强制转化为int64后使用FormatInt

//string 转为int
i, err := strconv.Atoi(s) 

int64 和 string 互转
//int64 转 string,第二个参数为基数
s := strconv.FormatInt(i64, 10)
// string 转换为 int64 
//第二参数为基数,后面为位数,可以转换为int32,int64等
i64, err := strconv.ParseInt(s, 10, 64) 

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)

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 
 

05-02 16:42