go interface{}类型转换

go interface{}类型转换


目录

  1. 查看interface{}类型
  2. 还原interface{}的原类型

1. 查看interface{}类型

func checkType(i interface{
    
    }) {
    
    
	reflect.TypeOf(i)
}

2. 还原interface{}的原类型

  1. 通过switch判断interface{}类型,然后通过 xxx.(类型) 强转
type Person struct {
    
    
	name string
	age  int
}

func checkType(i interface{
    
    }) {
    
    
	switch v := i.(type) {
    
     //这里是通过i.(type)来判断是什么类型  下面的case分支匹配到了 则执行相关的分支
	case int:
		fmt.Printf("%v is an int\n", v)
	case string:
		fmt.Printf("%v is string", v)
	case Person:
		fmt.Println("Person", reflect.TypeOf(i))
		i2 := i.(Person) //将 i 强转为 Person
		fmt.Println(i2.name)
	case bool:
		fmt.Printf("%v is bool", v)
	}
}

func main() {
    
    
	var info Person
	info.name = "zs"
	info.age = 20
	checkType(info)
}

猜你喜欢

转载自blog.csdn.net/weixin_41910694/article/details/111496784