Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable parameters to Sprintf in golang

Tags:

slice

go

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...)  
like image 377
Daniel YC Lin Avatar asked Jun 02 '15 06:06

Daniel YC Lin


People also ask

How do you pass variable arguments in Golang?

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.

What does Sprintf do in golang?

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.

What is a Variadic function in C?

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.


1 Answers

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
}
like image 80
icza Avatar answered Oct 16 '22 22:10

icza