这是接口列表的参数{}

时间:2018-07-02 19:25:45

标签: go interface

我正在尝试创建一个函数,该函数打印出传递给它的列表的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{}

1 个答案:

答案 0 :(得分:1)

您可以使用reflect软件包-playground

import (
    "fmt"
    "reflect"
)
func printLength(lis interface{}) {
    fmt.Printf("Length: %d", reflect.ValueOf(lis).Len())
}