go 数据类型转换

在编程过程中我们经常遇到各种数据类型的转换,例如 string 类型的转换成int
在go 里面使用strconv 包来实现

其他类型转string 使用Format系列函数来实现

来看demo

func FormatString()  {
    // Format 系列函数把其他类型的转换为字符串
    // bool 转string
    bool2str := strconv.FormatBool(true)
    // int 转string 
    // base:进位制(2 进制到 36 进制)
    int2str := strconv.FormatInt(123, 10)
    // Itoa 相当于 FormatInt(i, 10)
    int2ascii := strconv.Itoa(1)
    // float 转 string
    // fmt:格式标记(b、e、E、f、g、G)
    // prec:精度(数字部分的长度,不包括指数部分)
    // bitSize:指定浮点类型(32:float32、64:float64)
    float2str := strconv.FormatFloat(123.23, 'g', 12, 64)
    fmt.Println(bool2str+"000")
    fmt.Println(int2str)
    fmt.Println(int2ascii)
    fmt.Println(float2str)

string 转其他类型

func ParserString()  {
    // Parse 系列函数把字符串转换为其他类型
    str2bool, e1 := strconv.ParseBool("false")
    if e1 != nil {
        fmt.Println(str2bool)
    }
    str2int, e2 := strconv.Atoi("1024")
    if e2 != nil {
        fmt.Println(e2)
    }
    fmt.Println(str2int)

}

猜你喜欢

转载自blog.csdn.net/lucky404/article/details/81046808