我有这个功能:
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次吗?
答案 0 :(得分:5)
import "fmt"
显式参数索引:
在Printf,Sprintf和Fprintf中,默认行为是每个 格式化动词来格式化调用中传递的连续参数。 但是,动词前的符号[n]表示 而是将第n个单索引参数格式化。
您可以一次传递变量v
。例如,
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")))
}
游乐场:https://play.golang.org/p/DlafU_R_phq
输出:
CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);
答案 1 :(得分:0)
您也可以使用 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()
}