Get the length of a slice of unknown type
Asked Answered
M

1

5

Let's say I have a function that returns an interface{}. But I know that item returns is a slice of some kind. How can I determine the length of that slice? Here's sample code of what I tried, but they all cause compilation error.

package main

import (
  "log"
  "reflect"
)
func SomeKindOfSlice() interface{} {
  return []int64{0,1,2,3,4,5,6,7,8,9}
}
func main() {
  slice := SomeKindOfSlice()
  /*log.Println(reflect.TypeOf(slice).Len())
  log.Println(reflect.TypeOf(slice).Type().Len())
  log.Println(reflect.ValueOf(slice).Type().Len())
  log.Println(reflect.ValueOf(slice).Elem().Type().Len())
  */
  log.Println(reflect.ValueOf(slice).Elem().Type().Len())
}

I'd like to avoid the brute force way of specifically type asserting the slice variable just to find the length.

Monochromat answered 27/8, 2018 at 18:23 Comment(1)
reflect.ValueOf(slice).Len()Judicator
H
8

In your current attempt of the refect package usage you are querying for the Len of the Type. So this assumes you are dealing with an array not a slice. The difference being that a array is a fixed size slice, a slice has unbound length.

Check this code for demonstration

package main

import (
  "log"
  "reflect"
)
func SomeKindOfSlice() interface{} {
  return []int64{0,1,2,3,4,5,6,7,8,9}
}
func SomeKindOfArray() interface{} {
  return [10]int64{0,1,2,3,4,5,6,7,8,9}
}
func main() {
  log.Println(reflect.ValueOf(SomeKindOfSlice()).Len())
  log.Println(reflect.ValueOf(SomeKindOfArray()).Type().Len())
}
Hagan answered 27/8, 2018 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.