• [GO]断言


    使用if实现断言

    package main
    
    import "fmt"
    
    type Student struct {
        name string
        id int
    }
    
    func main() {
        i := make([]interface{}, 3)
        i[0] = 1
        i[1] = "hello world"
        i[2] = Student{"miki", 1}
        //类型查询,查询断言
        //第一个返回下标,第二个返回下标对应的值,data分别是i[0],i[1],i[2],
        for index, data := range i{
            //第一个返回的是值 ,第二个返回的是判断结果的真假
            if value, ok := data.(int); ok == true {
                fmt.Printf("x[%d]类型为int, 内容为%d
    ", index, value)
            }else if value, ok := data.(string); ok == true {
                fmt.Printf("x[%d]类型为string, 内容为%d
    ", index, value)
            }else if value, ok := data.(Student); ok == true {
                fmt.Printf("x[%d]Student, 内容为name=%s, id=%d
    ", index, value.name, value.id)
            }
        }
    }

    执行的结果为

    x[0]类型为int, 内容为1
    x[1]类型为string, 内容为%!d(string=hello world)
    x[2]Student, 内容为name=miki, id=1

    如果是使用switch的方式进行断言的话就会像这样

    package main
    
    import "fmt"
    
    type Student struct {
        name string
        id int
    }
    
    func main() {
        i := make([]interface{}, 3)
        i[0] = 1
        i[1] = "hello world"
        i[2] = Student{"miki", 1}
        //类型查询,查询断言
        //第一个返回下标,第二个返回下标对应的值,data分别是i[0],i[1],i[2],
        for index, data := range i{
            //第一个返回的是值 ,第二个返回的是判断结果的真假
            switch value := data.(type) { //这里是data.(type)的方式
            case int:
                fmt.Printf("x[%d]类型为int, 内容为%d
    ", index, value)
            case string:
                fmt.Printf("x[%d]类型为string, 内容为%d
    ", index, value)
            case Student:
                fmt.Printf("x[%d]Student, 内容为name=%s, id=%d
    ", index, value.name, value.id)
            }
        }
    }

    执行结果

    x[0]类型为int, 内容为1
    x[1]类型为string, 内容为%!d(string=hello world)
    x[2]Student, 内容为name=miki, id=1
  • 相关阅读:
    设计模式:访问者模式
    设计模式:模板模式
    三分法——求解凸性函数的极值问题——czyuan原创
    素数&&Miller_Rabbin
    【算法入门】深度优先搜索(DFS)
    快速幂取模
    hrbeu1280Turn the corner
    hdoj_3400Line belt
    【专题】三分法和牛顿迭代法总结
    zoj_3203Light Bulb
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9644209.html
Copyright © 2020-2023  润新知