cloudaice / learnGo

there are something about Go Useage
MIT License
0 stars 0 forks source link

interface{] 作为不定参数 #11

Open cloudaice opened 9 years ago

cloudaice commented 9 years ago

以interface{}类型作为不定参数的函数或者方法,在使用的时候需要注意以下问题:

type People struct {
    p string
}

func foo(v ...People) {
    fmt.Println(v)
}

func bar(v ...interface{}) {
    fmt.Println(v)
}

下面这段代码编译的时候会报错。

func main() {
    d := []People{People{"a"}, People{"b"}}
    bar(d...)
}

报错信息如下: cannot use d (type []People) as type []interface {} in argument to bar 而下面的代码实现,编译不会出现问题

func main() {
    d := []People{People{"a"}, People{"b"}}
    foo(d...)
}