go的数据类型转换

2019-06-26  本文已影响0人  魔法时刻
package main

import (
    "fmt"
    "unsafe"
)

func main() {
    // go 在不同数据类型之间需要显示转化 不能自动转换
    var i int32 = 100
    n1 := float32(i)
    fmt.Println(n1)
    fmt.Printf("n1的类型 %T    n1 占用的字节 %d\n", n1, unsafe.Sizeof(n1))
    fmt.Printf("i的类型 %T i 占用的字节 %d\n", i, unsafe.Sizeof(i))

    // T(v)将值 v 转换成类型 T
    // T 就是数据类型 int32 float64
    // v 就是需要转换的变量

    //被转换的是变量存储的数据,变量本身并无变化
}

基本数据类型转string

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var num1 uint8 = 99
    var num2 float32 = 123.456
    var b  = true
    var myChar byte = 'h'
    var str string

    //第一种转换方式
    str = fmt.Sprintf("%d", num1)
    fmt.Printf("str type is %T str = %q\n", str, str)

    str = fmt.Sprintf("%f", num2)
    fmt.Printf("str type is %T str = %q\n", str, str)

    str = fmt.Sprintf("%t", b)
    fmt.Printf("str type is %T str = %q\n", str, str)

    str = fmt.Sprintf("%c", myChar)
    fmt.Printf("str type is %T str = %q\n", str, str)

    //第二种转换方式 strconv 不推荐 局限性大
    var num3 uint8 = 99
    //var num4 float32 = 123.456
    var b2  = true

    str = strconv.FormatUint(uint64(num3),10)
    fmt.Printf("str type is %T str = %q\n", str, str)

    //str = strconv.FormatFloat(num4,'f',5,32)  // cannot use num4 (type float32) as type float64 in argument to strconv.FormatFloat
    fmt.Printf("str type is %T str = %q\n", str, str)

    str = strconv.FormatBool(b2)
    fmt.Printf("str type is %T str = %q\n", str, str)

    //other Itoa
    var num5 int  = 789
    str = strconv.Itoa(num5)
    fmt.Printf("str type is %T str = %q\n", str, str)

}

string 转基本数据类型

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var str = "true"
    var b bool
    b, _ = strconv.ParseBool(str)
    fmt.Printf("b type is %T b = %v\n", b, b)

    var str2 = "3699"
    var n1 int64
    n1, _ = strconv.ParseInt(str2, 10, 64)
    fmt.Printf("b type is %T b = %v\n", n1, n1)

    var str3 = "113.457"
    var f1 float64
    f1, _ = strconv.ParseFloat(str3, 64)
    fmt.Printf("b type is %T b = %v\n", f1, f1)

}

要确保string类型转换成有效的数据,否则转变为默认值

上一篇下一篇

猜你喜欢

热点阅读