zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    ES6的Iterator,jquery Fn
    html4,xhtml,html5发展历史
    浏览器Range,Selection等选中文本对象
    高效的插入子节点DocumentFragment
    Vue 性能优化track-by
    JS中先有Object还是先有Function?
    Unicode 与(UTF-8,UTF-16,UTF-32,UCS-2)
    FormData、Blob、File、ArrayBuffer数据类型
    jQuery 2.0.3 源码分析 事件绑定
    记录:springmvc + mybatis + maven 搭建配置流程
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9644209.html
Copyright © 2011-2022 走看看