4

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
7
  • 3
    Go has no covariant types. You need to stuff your items in jobList into a []interface{} first before passing the []interface{} to your function. BTW. Don't use interface{}. Commented Nov 26, 2015 at 13:53
  • @Volker why not interface{} ? Commented Nov 26, 2015 at 13:54
  • @Volker and what is difference between my code and this mgo insert method Commented Nov 26, 2015 at 13:57
  • Remove "..." 3 dots from "this.setItemList(jobColl, jobList...)", it should be this.setItemList(jobColl, jobList), jobList is already an array Commented Nov 26, 2015 at 14:23
  • @PrashantThakkar that is not right, jobList will become just one parameter, such as [3, 4, 5], if without ...., it becomes [[3, 4, 5]] Commented Nov 26, 2015 at 14:25

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.