I have an array of interfaces like this :
type Test struct {
Name string
}
func main() {
result := []Test{
Test{Name: "ahmad"},
Test{Name: "reza"},
}
dump(result)
}
How can I dump this array and make a string like this:
Name
ahmad
reza
I want something like this but with arrays.
Update
I don't want to dump Test interface...
I want to dump every interfaces.
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 {
s := reflect.ValueOf(item)
t := reflect.TypeOf(item)
for j := 0; j < s.NumField(); j++ {
fmt.Println(t.Field(j).Name)
}
}
}
}
}
Something like this. But the result is :
typ
ptr
flag
typ
ptr
flag
How can I change output to :
Name
Name
Your example could really use more details but here is my best attempt at helping you based off what you've provided. I'm assuming the definition of dump is as follows;
func dump(items []interface{})
And that you are specifically looking to print the Name
field on whatever is passed in, rather than say printing all fields on any object passed in.
func dump(items []interface{}) {
fmt.Println("Name")
for i := 0; i < len(items); i++ {
v := reflect.ValueOf(items[i])
name := v.FieldByName("Name")
fmt.Println(name.String())
}
}
Working example here; https://play.golang.org/p/zUBt6qkuok
If you instead want to print all fields that can be done with minor changes. Just add another loop inside of this where you iterate on j < v.NumField()
and use v.Field(i)
to get each field that's there. There are a lot of ways to structure your code at this level depending on what you want (like if you want to print FieldName1 followed by it's values then FieldName2 followed by it's values ect then your code would look quite different than if you weren't including the headers or printing each field on the current instance one after another). But these are details you'll have to worry about yourself or specify in an update to your question. Some good reading on the topic here; https://blog.golang.org/laws-of-reflection
Also the reflect packages docs are quite helpful.
I find a way !
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())
}
}
}
}
}
https://play.golang.org/p/JUAnVoSAwc
Thanks.