go interface{} type conversion

go interface{} type conversion


table of Contents

  1. View interface{} type
  2. Restore the original type of interface{}

1. View interface{} type

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

2. Restore the original type of interface{}

  1. Judge the interface{} type through switch, and then force it through xxx.(type)
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)
}

Guess you like

Origin blog.csdn.net/weixin_41910694/article/details/111496784