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...)
In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature. To declare a variadic function, the type of the final parameter is preceded by an ellipsis, "...", which shows that the function may be called with any number of arguments of this type.
Sprintf function in the GO programming language is a function used to return a formatted string. fmt. Sprintf supports custom format specifiers and uses a format string to generate the final output string.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With