在fmt.Sprintf格式字符串中多次引用相同的参数 [英] Refer to the same parameter multiple times in a fmt.Sprintf format string
本文介绍了在fmt.Sprintf格式字符串中多次引用相同的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个功能:
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
格式化字符串?
It's a little wonky... is there a way to format the string using 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次吗?
but without the need to pass v
4 times?
推荐答案
import "fmt"
显式参数索引:
在Printf,Sprintf和Fprintf中,默认行为是每个格式化动词来格式化调用中传递的连续参数.但是,动词前的符号[n]表示而是将第n个单索引参数格式化.
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(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);
这篇关于在fmt.Sprintf格式字符串中多次引用相同的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文