Iterate through the fields of a struct in Go

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

    Taking Chetan Kumar solution and in case you need to apply to a map[string]int

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type BaseStats struct {
        Hp           int
        HpMax        int
        Mp           int
        MpMax        int
        Strength     int
        Speed        int
        Intelligence int
    }
    
    type Stats struct {
        Base map[string]int
        Modifiers []string
    }
    
    func StatsCreate(stats BaseStats) Stats {
        s := Stats{
            Base: make(map[string]int),
        }
    
        //Iterate through the fields of a struct
        v := reflect.ValueOf(stats)
        typeOfS := v.Type()
    
        for i := 0; i< v.NumField(); i++ {
            val := v.Field(i).Interface().(int)
            s.Base[typeOfS.Field(i).Name] = val
        }
        return s
    }
    
    func (s Stats) GetBaseStat(id string) int {
        return s.Base[id]
    }
    
    
    func main() {
        m := StatsCreate(BaseStats{300, 300, 300, 300, 10, 10, 10})
    
        fmt.Println(m.GetBaseStat("Hp"))
    }
    
    
    

提交回复
热议问题