Skip to content

Instantly share code, notes, and snippets.

@zgiber
Created November 21, 2014 19:06
Show Gist options
  • Save zgiber/497d0ab83e49260fa107 to your computer and use it in GitHub Desktop.
Save zgiber/497d0ab83e49260fa107 to your computer and use it in GitHub Desktop.
Iterate struct fields using reflect in Go
package main
import "fmt"
import "reflect"
type Person struct {
Name string
Age int
Email string
}
func main() {
d1 := &Person{"Zoli", 34, "zoli@example.com"}
//d2 := &Person{"NemZoli", 12, "nemzoli@example.com"}
typed1 := reflect.TypeOf(d1)
valued1 := reflect.ValueOf(d1)
//nonPatchableFields := []string{"Name"}
numFields := typed1.Elem().NumField()
for i := 0 ; i < numFields; i++ {
ffmt.Println(typed1.Elem().Field(i).Name, valued1.Elem().Field(i).Interface())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment