Home >Backend Development >Golang >How to Pass Variable Parameters to Sprintf in Go with a Slice of Strings?
Passing Variable Parameters to Sprintf in Go
When working with a large number of parameters, manually passing them to Sprintf can be tedious. Fortunately, there is a way to simplify this process.
Issue:
Attempting to pass a slice of strings ([]string) directly to Sprintf results in an error:
cannot use v (type []string) as type []interface {} in argument to fmt.Printf
Solution:
To resolve this error, declare the slice as a type of []interface{} instead of []string. Sprintf expects an array of interface{} parameters, as seen in its signature:
func Printf(format string, a ...interface{}) (n int, err error)
Example:
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
Note:
[]interface{} and []string are not interchangeable. If you have an existing []string, you can manually convert it to []interface{} as follows:
ss := []string{"a", "b", "c"} is := make([]interface{}, len(ss)) for i, v := range ss { is[i] = v }
The above is the detailed content of How to Pass Variable Parameters to Sprintf in Go with a Slice of Strings?. For more information, please follow other related articles on the PHP Chinese website!