Go 类型断言和类型转换

Go About 795 words

示例

func main() {
    var i interface{} = "hello"

    s := i.(string)
    fmt.Println(s) // hello

    s, ok := i.(string)
    fmt.Println(s, ok) // hello true

    f, ok := i.(float64)
    fmt.Println(f, ok) // 0 false

    f = i.(float64) // panic 即使是字符串123也会panic 因为类型不同
    fmt.Println(f)
}

类型转换

使用t := i.(T)对已知interface{}进行转换。

类型断言后转换

方式一

使用t, ok := i.(T)对未知interface{}进行断言,若oktrue,则t赋值为转换后的值,若okfalse,则t为类型对应的默认值(如:int默认值是0string默认值是"")。

方式二

使用switch来判断object.(type)的类型并进行转换。

func Cast(object interface{}) {
    switch object.(type) {
    case string:
        fmt.Println("string#", object.(string))
    case int:
        fmt.Println("int#", object.(int))
    case float64:
        fmt.Println("float64#", object.(float64))
        // 其他类型
    }
}

参考

https://tour.golang.org/methods/15

Views: 1,270 · Posted: 2021-01-13

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh