Golang reflect.NumField()函数的示例

Golang reflect.NumField()函数的示例

Go语言提供了强大的运行时反射支持,利用反射包,程序可以操作具有任意类型的对象。Golang中的 reflect.NumField() 函数用于获取结构体v中的字段数量。要访问此函数,需要在程序中导入reflect包。

语法:

func (v Value) NumField() int

参数: 此函数不接受任何参数。

返回值: 此函数返回结构体v中字段的数量。

下面的示例演示了如何在Golang中使用上述方法:

示例1:

// Golang program to illustrate
// reflect.NumField() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
// Main function
func main() {
   
    // use of StructOf method
    tt:= reflect.StructOf([]reflect.StructField{
        {
            Name: "Height",
            Type: reflect.TypeOf(0.0),
            Tag:  `json:"height"`,
        },
        {
            Name: "Name",
            Type: reflect.TypeOf("abc"),
            Tag:  `json:"name"`,
        },
    })
   
    fmt.Println(tt.NumField()) 
   
} 

输出结果:

2

示例2:

// Golang program to illustrate
// reflect.NumField() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
type temp struct {  
    ord      int
    cId int
}
    
// function to use the 
// Field() 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程