如何在golang中声明一个函数接受一个接口数组?

时间:2015-11-26 13:47:34

标签: go

我想声明一个函数接受接口数组,例如:

func (this *CvStoreServiceImpl) setItemList(coll *mgo.Collection, itemList ...interface{}) (err error)

Howerver,当我把这个函数称为跟随失败时:

jobList := cvRaw.GetJobList()
this.setItemList(jobColl, jobList...)

这里出现错误:

cannot use cvRaw.GetJobList() (type []*cv_type.CvJobItemRaw) as type []interface {} in argument to this.setItemList

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找is this

package main

import "fmt"

func main() {
    interfacetious := []interface{}{"s", 123, float64(999)}
    stuff(interfacetious)
    stuff2(interfacetious...)

    stuff2("or", 123, "separate", float64(99), "values")
}

// Stuff can only work with slice of things
func stuff(s []interface{}) {
    fmt.Println(s)
}

// Stuff2 is polyvaridc and can handle individual vars, or a slice with ...
func stuff2(s ...interface{}) {
    fmt.Println(s)
}

答案 1 :(得分:1)

假设您要使用可变参数,则问题正确声明了setItemList方法。由于setList函数适用于任何Mongo文档类型,因此在这种情况下使用interface{}是合适的。

[]*cv_type.CvJobItemRaw无法转换为[]interface{}。编写循环以从[]interface{}创建jobList

jobList := cvRaw.GetJobList()
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}
this.setItemList(jobColl, s...)

有关更多详细信息,请参见Go Language FAQ