gogofmt

How to index parameters when formatting a string in Go


Let's say I have a string "Hello %s. How are you %s" and I want to put the same string in both of %s. The obvious option is to use:

fmt.Printf("Hello %s. How are you %s", "KK", "KK") // returns "Hello KK. How are you KK"

is there a way to index the parameters so that I don't have to repeat "KK"?


Solution

  • Found a way to do it. The syntax is as follows:

    fmt.Printf("Hello %[1]s. How are you %[1]s", "KK") // returns "Hello KK. How are you KK"
    

    where %[1]s represents the first parameter after the string that is being formatted. You can also do something like this:

    fmt.Printf("Hello %[1]s. How are you %[1]s. Where are you %[2]s", "KK", "today") // returns "Hello KK. How are you KK. Where are you today"