英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论