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

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年11月26日 21:47:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/33940337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定