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
  • 相关阅读:
    ci
    RN开发杂记
    ‘100%’wuxiao
    Statezhong shiyong redux props
    assemble、compile、make、build和rebuild的关系
    promise
    React Native 通过navigation实现页面间传值
    react native redux
    js中 === 整形和字符串比较
    React Native 中使用Redux
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9644209.html
Copyright © 2011-2022 走看看