英文:
how to declare a function accept an array of interface in golang?
问题
我想声明一个接受接口数组的函数,就像这样:
func (this *CvStoreServiceImpl) setItemList(coll *mgo.Collection, itemList ...interface{}) (err error)
然而,当我像下面这样调用这个函数时失败了:
jobList := cvRaw.GetJobList()
this.setItemList(jobColl, jobList...)
这里是错误信息:
无法将 cvRaw.GetJobList()(类型为 []*cv_type.CvJobItemRaw)作为参数传递给 this.setItemList,类型不匹配,需要 []interface{}
英文:
I want to declare a function accept array of interface, such as this:
func (this *CvStoreServiceImpl) setItemList(coll *mgo.Collection, itemList ...interface{}) (err error)
Howerver, when I call this function like as follow failed:
jobList := cvRaw.GetJobList()
this.setItemList(jobColl, jobList...)
here this the error:
cannot use cvRaw.GetJobList() (type []*cv_type.CvJobItemRaw) as type []interface {} in argument to this.setItemList
答案1
得分: 2
我认为你正在寻找的是这个:
package main
import "fmt"
func main() {
interfacetious := []interface{}{"s", 123, float64(999)}
stuff(interfacetious)
stuff2(interfacetious...)
stuff2("or", 123, "separate", float64(99), "values")
}
// Stuff 只能处理一组事物的切片
func stuff(s []interface{}) {
fmt.Println(s)
}
// Stuff2 是多变量函数,可以处理单个变量或带有...的切片
func stuff2(s ...interface{}) {
fmt.Println(s)
}
你可以在这里找到代码:链接
英文:
I think what you're looking for 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)
}
答案2
得分: 2
问题正确地声明了setItemList
方法,假设你想要一个可变参数。因为setList
函数适用于任何Mongo文档类型,在这种情况下使用interface{}
是合适的。
[]*cv_type.CvJobItemRaw
不能转换为[]interface{}
。请编写一个循环,从jobList
创建[]interface{}
。
jobList := cvRaw.GetJobList()
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
this.setItemList(jobColl, s...)
有关更多详细信息,请参阅Go语言FAQ。
英文:
The question correctly declares the setItemList
method, assuming that you want a variadic argument. Because the setList
function works with any Mongo document type, it is appropriate to use interface{}
in this scenario.
A []*cv_type.CvJobItemRaw
cannot be converted to a []interface{}
. Write a loop to create the []interface{}
from jobList
.
jobList := cvRaw.GetJobList()
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
this.setItemList(jobColl, s...)
See the Go Language FAQ for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论