Skip to content

Instantly share code, notes, and snippets.

@ahmdrz
Created September 23, 2016 08:07
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ahmdrz/5448c37063d3757b5581fb8df53800e0 to your computer and use it in GitHub Desktop.
Save ahmdrz/5448c37063d3757b5581fb8df53800e0 to your computer and use it in GitHub Desktop.
Golang Reflection Example of an array.
package main
import (
"fmt"
"reflect"
)
type Test struct {
Name string
}
func main() {
result := []Test{
Test{Name: "ahmad"},
Test{Name: "reza"},
}
dump(result)
}
func dump(datasets interface{}) {
items := reflect.ValueOf(datasets)
if items.Kind() == reflect.Slice {
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
if item.Kind() == reflect.Struct {
v := reflect.Indirect(item)
for j := 0; j < v.NumField(); j++ {
fmt.Println(v.Type().Field(j).Name, v.Field(j).Interface())
}
}
}
}
}
@ahmdrz
Copy link
Author

ahmdrz commented Sep 23, 2016

@digifoxman
Copy link

Hi Ahmad, tnx a lot for this sample. Exactly what I needed: how to use reflection on an array of unknown structs. Best regards, Ulfert.

@ahmdrz
Copy link
Author

ahmdrz commented Apr 17, 2020

Your welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment