2 回答
TA贡献1893条经验 获得超10个赞
您可以通过反射值循环使用 switch,这将返回reflect.Value kind() 以返回该值的确切类型
v := reflect.ValueOf(s interface{})
for t := 0; i < v.NumField(); i++ {
fmt.Println(v.Field(i)) // it will prints the value at index in interface
switch t := v.Kind() {
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
}
}
要将接口中的类型转换为另一种类型,首先在变量中获取它的值,然后使用类型转换来转换该值
- 2 回答
- 0 关注
- 459 浏览
添加回答
举报