How to index parameters when formatting a string in Go

huangapple go评论154阅读模式
英文:

How to index parameters when formatting a string in Go

问题

假设我有一个字符串 "Hello %s. How are you %s",我想在两个 %s 中放入相同的字符串。显而易见的选项是使用:

fmt.Printf("Hello %s. How are you %s", "KK", "KK") // 返回 "Hello KK. How are you KK"

有没有一种方法可以对参数进行索引,以便我不必重复 "KK"

英文:

Let's say I have a string "Hello %s. How are you %s" and I want to put the same string in both of %s. The obvious option is to use:

fmt.Printf("Hello %s. How are you %s", "KK", "KK") // returns "Hello KK. How are you KK"

is there a way to index the parameters so that I don't have to repeat "KK"?

答案1

得分: 1

找到了一种方法来实现。语法如下:

fmt.Printf("Hello %[1]s. How are you %[1]s", "KK") // 返回 "Hello KK. How are you KK"

其中 %[1]s 表示字符串格式化后的第一个参数。你也可以这样做:

fmt.Printf("Hello %[1]s. How are you %[1]s. Where are you %[2]s", "KK", "today") // 返回 "Hello KK. How are you KK. Where are you today"
英文:

Found a way to do it. The syntax is as follows:

fmt.Printf("Hello %[1]s. How are you %[1]s", "KK") // returns "Hello KK. How are you KK"

where %[1]s represents the first parameter after the string that is being formatted. You can also do something like this:

fmt.Printf("Hello %[1]s. How are you %[1]s. Where are you %[2]s", "KK", "today") // returns "Hello KK. How are you KK. Where are you today"

huangapple
  • 本文由 发表于 2022年10月31日 14:57:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/74259690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定