简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM