Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fmt.Sprintf passing an array of arguments

Tags:

format

go

Sorry for the basic question. I'd like to pass a slice as arguments to fmt.Sprintf. Something like this:

values := []string{"foo", "bar", "baz"}
result := fmt.Sprintf("%s%s%s", values...)

And the result would be foobarbaz, but this obviously doesn't work.

(the string I want to format is more complicated than that, so a simple concatenation won't do it :)

So the question is: if I have am array, how can I pass it as separated arguments to fmt.Sprintf? Or: can I call a function passing an list of arguments in Go?

like image 292
moraes Avatar asked Aug 22 '11 10:08

moraes


People also ask

What does FMT Sprintf do?

The fmt. 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 FMT in Go language?

fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.


1 Answers

As you found out on IRC, this will work:

values := []interface{}{"foo", "bar", "baz"}
result := fmt.Sprintf("%s%s%s", values...)

Your original code doesn't work because fmt.Sprintf accepts a []interface{} and []string can't be converted to that type, implicitly or explicitly.

like image 71
Evan Shaw Avatar answered Oct 05 '22 02:10

Evan Shaw