-3

I know how to pass it when the arguments are ... strings

But this case is a bit different:

func main() {
    args := []string{"hello", "world"}
    fmt.Println(args...)
}

https://play.golang.org/p/7ELdQQvdPvR

The above code throws the error cannot use args (type [] string) as type [] interface {} in argument to fmt.Println

What would be the most idiomatic way to achieve this?

capipo
  • 67
  • 1
  • 6

1 Answers1

0

This can be done in one of two ways:

   args := []interface{}{"hello", "world"}
   fmt.Println(args...)

Or:

  args:=[]string{"hello", "world"}
  iargs:=make([]interface{},0)
  for _,x:=range args {
     iargs=append(iargs, x)
  }
  fmt.Println(iargs...)

You can pass a string where an interface{} is required, but you can't pass a []string where a []interface{} required. The compiler converts string value to an interface{} value, but that is not done for arrays, and you have to do the translation yourself.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59