golang 类型断言

函数使用 interface{} 作为参数时,可以接收各种类型的数据。使用的时候通常需要判断具体是哪一种类型,并且将 interface{} 转成这个类型,这时候就需要类型断言。

语法

具体类型匹配

x.(string)
x.(int)
x.(bool)
x.(int32)

switch case 中匹配

    switch i.(type) {
	case string:
		fmt.Println("is string")
	case int:
		fmt.Println("is int")
    }

示例

基本类型

package main

import "fmt"

func f(i interface{}) {
    v, ok := i.(string)
    if ok {
        fmt.Println("ok, string is:", v)
    }
    switch i.(type) {
        case string:
        fmt.Println(i, "is string")
        case int:
        fmt.Println(i, "is int")
    }
}

func main() {
    i := "hefs"
    f(i)
	a := 33
	f(a)
}

结构体类型

package main

import "fmt"

type People struct {
    Name string
    Age int
    No int
}
type Student struct {
    SNo int
    People
}

func main() {
    s := Student{1, People{"kika", 33, 1}}
    f(s)
    
    p := People{"lisi", 22, 123}
    f(p)
}

func f(i interface{}) {
    v, ok := i.(Student)
    if ok {
        // fmt.Printf("SNo is: %v\n", i.SNo)
        fmt.Printf("SNo is: %v\n", v.SNo)
        fmt.Printf("%#v is Student, after convert is: \n%#v\n", i, v)
    }
    v2, ok2 := i.(People)
    if ok2 {
        // fmt.Printf("SNo is: %v\n", i.No)
        fmt.Printf("SNo is: %v\n", v2.No)
        fmt.Printf("%#v is People, after convert is: \n%#v\n", i, v2)
    }
}

输出:

SNo is: 1
main.Student{SNo:1, People:main.People{Name:"kika", Age:33, No:1}} is Student, after convert is: 
main.Student{SNo:1, People:main.People{Name:"kika", Age:33, No:1}}
SNo is: 123
main.People{Name:"lisi", Age:22, No:123} is People, after convert is: 
main.People{Name:"lisi", Age:22, No:123}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值