Search code examples
gostring-formatting

Refer to the same parameter multiple times in a fmt.Sprintf format string


I have this function:

func getTableCreationCommands(v string) string {
    return `
        CREATE TABLE share_` + v + ` PARTITION OF share FOR VALUES IN (` + v + `);
        CREATE TABLE nearby_` + v + ` PARTITION OF nearby FOR VALUES IN (` + v + `);
    `
}

It's a little wonky... is there a way to format the string using fmt.Sprintf?

Something like this:

func getTableCreationCommands(v string) string {
    return fmt.Sprintf(`
        CREATE TABLE share_%v PARTITION OF share FOR VALUES IN (%v);
        CREATE TABLE nearby_%v PARTITION OF nearby FOR VALUES IN (%v);
    `, v, v, v, v)
}

but without the need to pass v 4 times?


Solution

  • Package fmt

    import "fmt" 
    

    Explicit argument indexes:

    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.


    You can pass the variable v once. For example,

    package main
    
    import "fmt"
    
    func getTableCreationCommands(s string) string {
        return fmt.Sprintf(`
            CREATE TABLE share_%[1]v PARTITION OF share FOR VALUES IN (%[1]v);
            CREATE TABLE nearby_%[1]v PARTITION OF nearby FOR VALUES IN (%[1]v);
        `, s)
    }
    
    func main() {
        fmt.Println(getTableCreationCommands(("X")))
    }
    

    Playground: https://play.golang.org/p/fKV3iviuwll

    Output:

    CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
    CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);