7.2 Go type assertion

 7.2 Go type assertion

类型断言是使用在接口值上的操作。

语法x.(T)被称为类型断言,x代表接口的类型,T代表一个类型检查。

类型断言检查它操作对象的动态类型是否和断言类型匹配

类型断言快速入门

package main

import (
    "fmt"
)

type Point struct {
    x int
    y int
}

func main() {

    var a interface{}
    var point Point = Point{1, 2}
    //任何类型都实现了空接口
    a = point
    fmt.Printf("类型:%T 值:%v
", a, a)

    /*
        想要将a赋值给b变量,可以直接这么玩吗?
        var b Point
        b = a
        报错
        cannot use a (type interface {}) as type Point in assignment: need type assertion
        提示需要类型断言type assertion
    */
    var b Point
    b, ok := a.(Point)
    if ok {
        fmt.Printf("类型:%T 值:%v
", b, b)
    }
}

1.1. 类型断言介绍

在类型断言时,如果类型不匹配,程序会直接panic异常退出,因此要确保类型断言,空接口指向的就是断言的类型,或者加上检查机制,防止程序panic退出。

package main

import (
    "fmt"
)

//test函数接收一个空接口,可以接收任意的数据类型
func test(a interface{}) {

    //带有检查机制的类型断言,ok是布尔值,返回true或false
    s, ok := a.(int)
    if ok {
        fmt.Println(s)
        //手动return结束这个类型检查
        return
    }

    str, ok := a.(string)
    if ok {
        fmt.Println(str)
        return
    }

    f, ok := a.(float32)
    if ok {
        fmt.Println(f)
        return
    }

    fmt.Println("can not define the type of a")
}

//测试test函数类型检查
func testInterface1() {
    var a int = 100
    test(a)

    var b string = "hello"
    test(b)
}

//使用分支判断,检测类型断言
func testSwitch(a interface{}) {
    //直接switch跟着类型断言表达式
    switch a.(type) {
    case string:
        fmt.Printf("a is string, value:%v
", a.(string))
    case int:
        fmt.Printf("a is int, value:%v
", a.(int))
    case int32:
        fmt.Printf("a is int, value:%v
", a.(int))
    default:
        fmt.Println("not support type
")
    }
}

func testSwitch2(a interface{}) {
    //将类型断言结果赋值给变量
    switch v := a.(type) {
    case string:
        fmt.Printf("a is string, value:%v
", v)
    case int:
        fmt.Printf("a is int, value:%v
", v)
    case int32:
        fmt.Printf("a is int, value:%v
", v)
    default:
        fmt.Println("not support type
")
    }
}

func testInterface2() {
    var a int = 123456
    testSwitch(a)
    fmt.Println("-------------")
    var b string = "hello"
    testSwitch(b)
}

func testInterface3() {
    var a int = 100
    testSwitch2(a)
    var b string = "hello"
    testSwitch2(b)
}

func main() {
    //testInterface1()
    //testInterface2()
    testInterface3()
}
原文地址:https://www.cnblogs.com/open-yang/p/11256893.html