learningtech
learningtech

Reputation: 33683

Get the length of a slice of unknown type

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.

Upvotes: 5

Views: 3828

Answers (1)

user4466350
user4466350

Reputation:

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())
}

Upvotes: 8

Related Questions