Go 语言字符串和数字转化 | 臭大佬

臭大佬 2020-08-19 23:46:09 1053
Go 
简介 Go 语言字符串和数字转化 | 臭大佬

代码

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "17"
    int0, err0 := strconv.Atoi(str)
    fmt.Printf("string到int,默认值: %v\n", str)
    if err0 != nil {
        fmt.Printf("...报错了\n")
    } else {
        fmt.Printf("...转化前:%T\n", str)
        fmt.Printf("...转化后:%T\n", int0)
    }

    fmt.Printf("string到int64,默认值: %v\n", str)
    int1, err1 := strconv.ParseInt(str, 10, 64)
    if err1 != nil {
        fmt.Printf("...报错了\n")
    } else {
        fmt.Printf("...转化前:%T\n", str)
        fmt.Printf("...转化后:%T\n", int1)
    }

    int2 := 12
    str2 := strconv.Itoa(int2)
    fmt.Printf("int到string,默认值: %v\n", int2)
    fmt.Printf("...转化前:%T\n", int2)
    fmt.Printf("...转化后:%T\n", str2)

    var int3 int64
    str3 := strconv.FormatInt(int3, 10)
    fmt.Printf("int64到string,默认值: %v\n", int3)
    fmt.Printf("...转化前:%T\n", int3)
    fmt.Printf("...转化后:%T\n", str3)

    // 结果
    //string到int,默认值: 17
    //...转化前:string
    //...转化后:int
    //string到int64,默认值: 17
    //...转化前:string
    //...转化后:int64
    //int到string,默认值: 12
    //...转化前:int
    //...转化后:string
    //int64到string,默认值: 0
    //...转化前:int64
    //...转化后:string

}