gogofmt

How to format a string containing a dynamic number of elements?


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

Solution

  • 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