Skip to content

Instantly share code, notes, and snippets.

@wactbprot
Created December 30, 2016 12:24
Show Gist options
  • Save wactbprot/5180dc617cbb232a3faf86a180fc6a52 to your computer and use it in GitHub Desktop.
Save wactbprot/5180dc617cbb232a3faf86a180fc6a52 to your computer and use it in GitHub Desktop.
not very nice way to iterate over a struct using reflect in golang
// ...
type Config struct {
Db Conf `json:"db"`
Relay Conf `json:"relay"`
Redis Conf `json:"redis"`
}
type Conf struct {
Path string `json:"path"`
Port string `json:"port"`
Server string `json:"server"`
}
// ...
typ := reflect.TypeOf(co)
val := reflect.ValueOf(co)
for i := 0; i < val.NumField(); i++ {
fn := typ.Field(i).Name // Db, Redis ...
log.Debug(fn)
for j := 0; j < val.FieldByName(fn).NumField(); j++ {
ttyp, _ := typ.FieldByName(fn)
log.Debug( ttyp.Type.Field(j).Name) // Path, Port ..
log.Debug( val.FieldByName(fn).Field(j).String()) // values
}
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment