goprintf

Positional arguments in Go Printf?


In many other modern languages, "printf" type facilities allow the selection of arguments for substitution into the format string by their numerical position, rather than only in the order they appear. E.g. in Java:

System.out.printf("This is arg 2 %2$s and this is arg 1 %1$s\n", "first", "second")

produces the output:

This is arg 2 second and this is arg 1 first

I believe this is even specified by Posix in some context, since localization often requires language-specific word order.

Does Go support this capability? I've tried the obvious format string, but that didn't work.


Solution

  • Yes, that is possible; from the docs:

    In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead.

    Applying this to your example, you would have

    fmt.Printf("This is arg 2 %[2]s and this is arg 1 %[1]s\n", "first", "second")
    // prints 'This is arg 2 second and this is arg 1 first'