Finding length of arrays of structs

I have arrays of various structs and need to find their length … see example below

package main

import (
        "fmt"
)

type X struct {
        S string
}
type Y struct {
        N int
}

func main() {
        type t interface{}
        var x, y t
        x = []X{{S: "xxx"}, {S: "zzz"}}
        y = []Y{{N: 4}, {N: 5}, {N: 3}}
        Process(x, y)
}
func Process(i ...interface{}) {
        for _, v := range i {
                fmt.Println(v)
                fmt.Println(len(v))
        }
}
1 Like
package main

import (
	"fmt"
	"reflect"
)

type X struct {
	S string
}

type Y struct {
	N int
}

func Process(i ...interface{}) {
	for _, v := range i {
		s := reflect.ValueOf(v)
		if s.Kind() != reflect.Slice {
			continue
		}
		fmt.Println(s.Len(), s)
	}
}

func main() {
	type t interface{}
	var x, y t
	x = []X{{S: "xxx"}, {S: "zzz"}}
	y = []Y{{N: 4}, {N: 5}, {N: 3}}
	Process(x, y)
}

https://play.golang.org/p/uZQ_7xZ4N-7

2 [{xxx} {zzz}]
3 [{4} {5} {3}]

Package reflect

The Go Blog: The Laws of Reflection

Many thanks petrus … obviously I need to read that chapter in Donovan and Kernighan that I keep putting off :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.