码迷,mamicode.com
首页 > 其他好文 > 详细

类型断言

时间:2018-11-15 13:43:35      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:ack   package   print   for   printf   func   name   UNC   pre   

类型断言

package main

import (
    "fmt"
)

func main() {
    var p *person = new(person)
    fmt.Println(p)
    //
    i := make([]interface{}, 3) //切片类型:空接口,长度:3
    i[0] = 9
    i[1] = "string"
    i[2] = person{"张三", 30}
    fmt.Printf("%T\n", i)
    for index, data := range i {
        //if实现断言
        if value, ok := data.(int); ok == true {
            fmt.Printf("i[%d] 的类型为int, 值为 :%d\n", index, value)
        } else if value, ok := data.(string); ok == true {
            fmt.Printf("i[%d] 的类型为string, 值为 :%s\n", index, value)
        } else if value, ok := data.(person); ok == true {
            fmt.Printf("i[%d] 的类型为student, 值为 :%+v\n", index, value)
        }
        //switch实现断言
        switch value := data.(type) {
        case int:
            fmt.Printf("i[%d] 的类型为int, 值为 :%d\n", index, value)
        case string:
            fmt.Printf("i[%d] 的类型为string, 值为 :%s\n", index, value)
        case person:
            fmt.Printf("i[%d] 的类型为student, 值为 :%+v\n", index, value)
        }
    }
}

type person struct {
    name string
    age  int
}

 

类型断言

标签:ack   package   print   for   printf   func   name   UNC   pre   

原文地址:https://www.cnblogs.com/mask-fan/p/9962742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!