在 2016年9月23日星期五 UTC+8下午12:13:04,Lax Clarke写道:
>
> 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
>

[]interface{} is a concrete type, which is miss-match with []int{}. You may 
use interface{} as formal parameter but call the function with a 
[]interface{}

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


-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to