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
", s[1], s[2], s[3])
v := s[1:]
fmt.Printf("%5s %4s %3s
", v...)
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
", s[1], s[2], s[3])
v := s[1:]
fmt.Printf("%5s %4s %3s
", 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
}