Assuming that you could write a Len function as you specified, what would you do next? What problem are you trying to solve?
How would someone create a function like len ?func Len(s []interface{}) would not work because compiler complains of type mismatch if you call it with an integer slice (for example)Thanks
package main
import "fmt"import "reflect"
func Len(v interface{}) int { var length int
switch reflect.TypeOf(v).Kind() { // return the length of slice, use // func (v Value) Len() int case reflect.Slice: length = reflect.ValueOf(v).Len()
// return the length of int, or whatever you want case reflect.Int:
// ... }
return length}
type X struct { a, b int}
func main() { a := []int{1,2,3} // a typed slice, all elements' type is concrete (int) b := []interface{}{1, "11", 12.345, X{1, 2}} // still a typed slice, all elements' type is dynamic (interface) fmt.Println(Len(a), Len(b))}
There are two ways, one is to use reflection, the other would be to use unsafe to convert the slice value into another structure then extract the length field.Assuming that you could write a Len function as you specified, what would you do next? What problem are you trying to solve?