Created
December 30, 2016 12:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
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