Go语言提供了运行时反射的内置支持实现,并允许程序借助反射包来操纵任意类型的对象。 Golang中的reflect.Kind()函数用于查找种类名称。要访问此函数,需要在程序中导入反射包。
用法:
func (k Kind) String() string
以下示例说明了以上方法在Golang中的用法:
范例1:
// 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) 
  
}
输出:
Type main.temp Kind struct
范例2:
// 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) 
  
}
输出:
Number of fields 2 Field:0 type:reflect.Value value:1 Field:1 type:reflect.Value value:513