Iterate through the fields of a struct in Go

前端 未结 4 1488
野的像风
野的像风 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:21

    Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type person struct {
        firsName string
        lastName string
        iceCream []string
    }
    
    func main() {
        u := struct {
            myMap    map[int]int
            mySlice  []string
            myPerson person
        }{
            myMap:   map[int]int{1: 10, 2: 20},
            mySlice: []string{"red", "green"},
            myPerson: person{
                firsName: "Esmaeil",
                lastName: "Abedi",
                iceCream: []string{"Vanilla", "chocolate"},
            },
        }
        v := reflect.ValueOf(u)
        for i := 0; i < v.NumField(); i++ {
            fmt.Println(v.Type().Field(i).Name)
            fmt.Println("\t", v.Field(i))
        }
    }
    
    and there is no *panic* for v.Field(i)
    

提交回复
热议问题