2

I am trying to format a string based on the elements received from the function calling it. This number of elements can varyfrom one to many.

Is there a way to call fmt.Sprintf with a variable number of elements. Something along the lines of:

receivedElements := []interface{}{"some","values"}
formattedString := fmt.Sprintf("Received elements: ...%s", receivedElements...)

Output: Received elements: some values
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • The capability of the `fmt` package is specified in its [documentation](https://golang.org/pkg/fmt/) and what you're looking for is not there, at least I wasn't able to find it. This means you'll have to write your own solution if passing the slice as is is not good enough. – mkopriva Nov 28 '19 at 19:47
  • 1
    Also if all that bothers you are the square brackets around the values when you pass a slice to `fmt` you could always just slice those brackets away https://play.golang.com/p/eGBhnsXqWNO – mkopriva Nov 28 '19 at 19:52

1 Answers1

3

You can use https://golang.org/pkg/strings/#Repeat like that:

args := []interface{}{"some", "values"}
fmt.Println(fmt.Sprintf("values: " + strings.Repeat("%s ", len(args)), args...))

https://play.golang.org/p/75J6i2fSCaM

Or if you don't want to have last space in the line, you can create slice of %s and then use https://golang.org/pkg/strings/#Join

args := []interface{}{"some", "values"}
ph := make([]string, len(args))
for i, _ := range args {
    ph[i] = "%s"
}
fmt.Println(fmt.Sprintf("values: " + strings.Join(ph, ", "), args...))

https://play.golang.org/p/QNZT-i9Rrgn

Nikita Leshchev
  • 1,784
  • 2
  • 14
  • 26