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
  • 相关阅读:
    centos通过yum安装php
    CentOS6 用yum安装mysql详解,简单实用
    启用CentOS6.5 64位安装时自带的MySQL数据库服务器
    Python三方库:Pandas(数据分析)
    Python三方库:Numpy(数组处理)
    Java笔记:反射,注解
    Java笔记:多线程
    Java笔记:IO流
    Java笔记:集合
    Java笔记:数组,异常,泛型
  • 原文地址:https://www.cnblogs.com/baylorqu/p/9644209.html
Copyright © 2011-2022 走看看