我正在尝试创建一个函数,该函数打印出传递给它的列表的len
,而与列表的类型无关。我天真的做法是:
func printLength(lis []interface{}) {
fmt.Printf("Length: %d", len(lis))
}
但是,当尝试通过
使用它时func main() {
strs := []string{"Hello,", "World!"}
printLength(strs)
}
它抱怨说
cannot use strs (type []string) as type []interface {} in argument to printLength
但是,string
可以用作interface{}
,为什么不能将[]string
用作[]interface{}
?
答案 0 :(得分:1)
您可以使用reflect软件包-playground
import (
"fmt"
"reflect"
)
func printLength(lis interface{}) {
fmt.Printf("Length: %d", reflect.ValueOf(lis).Len())
}