8

I'm lazy, want to pass many variables to Printf function, is it possible? (The sample code is simplified as 3 parameters, I require more than 10 parameters).

I got the following message:

cannot use v (type []string) as type []interface {} in argument to fmt.Printf

s := []string{"a", "b", "c", "d"}  // Result from regexp.FindStringSubmatch()
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])  

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)  
Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96

1 Answers1

14

Yes, it is possible, just declare your slice to be of type []interface{} because that's what Printf() expects. Printf() signature:

func Printf(format string, a ...interface{}) (n int, err error)

So this will work:

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)

Output (Go Playground):

b    c   d
b    c   d

[]interface{} and []string are not convertible. See this question+answers for more details:

Type converting slices of interfaces in go

If you already have a []string or you use a function which returns a []string, you have to manually convert it to []interface{}, like this:

ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827