Iterate through the fields of a struct in Go

前端 未结 4 1479
野的像风
野的像风 2020-11-28 20:55

Basically, the only way (that I know of) to iterate through the values of the fields of a struct is like this:

type Example struct {
    a_numbe         


        
4条回答
  •  时光取名叫无心
    2020-11-28 21:06

    If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type Student struct {
        Fname  string
        Lname  string
        City   string
        Mobile int64
    }
    
    func main() {
        s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
        v := reflect.ValueOf(s)
        typeOfS := v.Type()
    
        for i := 0; i< v.NumField(); i++ {
            fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
        }
    }
    

    Run in playground

    Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

提交回复
热议问题