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
  • 相关阅读:
    android 拖放功能
    android 桌面文件夹ui美化
    instanceof 杂谈
    Android自定义长按事件
    launcher in android
    类似网易163TAB选项卡(标签)代码
    【新手入门教程】简洁纯CSS下拉导航菜单代码
    橘黄色的大气CSS菜单代码
    Flash效果的网站后台左侧Js多级展开菜单代码
    仿FLASH动感十足鼠标滑过放大的菜单代码
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9644209.html
Copyright © 2011-2022 走看看