在 fmt.Sprintf 格式字符串中多次引用同一参数

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

我有这个功能:

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 + `);
    `
}

有点靠不住...有没有办法使用 fmt.Sprintf 格式化字符串?

像这样:

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)
}

但不需要通过 v 4 次?

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.


你可以传递变量v一次。例如,

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")))
}

游乐场:https://play.golang.org/p/fKV3iviuwll

输出:

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

您也可以使用 text/template:

package same

import (
   "strings"
   "text/template"
)

func getTableCreationCommands(v string) string {
   t, b := new(template.Template), new(strings.Builder)
   template.Must(t.Parse(`
CREATE TABLE nearby_{{.}} PARTITION OF nearby FOR VALUES IN ({{.}});
CREATE TABLE share_{{.}} PARTITION OF share FOR VALUES IN ({{.}});
   `)).Execute(b, v)
   return b.String()
}

https://pkg.go.dev/text/template