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

南楼画角 提交于 2019-12-05 20:40:12

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(v 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);
    `, v)
}

func main() {
    fmt.Println(getTableCreationCommands(("X")))
}

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

Output:

CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!