Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Kind()函数用于查找种类的名称。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function does not takes any parameters.
Return Value: This function returns string (the name of kind).
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (k Kind) String() string
输出:
// Golang program to illustrate
// reflect.Kind() Function
package main
import (
"fmt"
"reflect"
)
type temp struct {
ord int
cId int
}
// function to use the
// Kind() method
func useKind(val interface{}) {
s1 := reflect.TypeOf(val)
// Kind() function is used
// to find the kind
s2 := s1.Kind()
fmt.Println("Type ", s1)
fmt.Println("Kind ", s2)
}
// Main function
func main() {
val := temp{
ord: 1,
cId: 513,
}
useKind(val)
}
示例 2:
Type main.temp
Kind struct
输出:
// Golang program to illustrate
// reflect.Kind() Function
package main
import (
"fmt"
"reflect"
)
type temp struct {
ord int
cId int
}
// function to use the
// Kind() method
func useKind(val interface{}) {
// Kind() function is used
// to find the kind
if reflect.ValueOf(val).Kind() == reflect.Struct {
v := reflect.ValueOf(val)
fmt.Println("Number of fields", v.NumField())
for i := 0; i < v.NumField(); i++ {
fmt.Printf("Field: %d \t type: %T \t value: %v\n",
i, v.Field(i), v.Field(i))
}
}
}
// Main function
func main() {
val := temp{
ord: 1,
cId: 513,
}
useKind(val)
}