在`fmt.Printf`中,有没有一种方法可以重复使用一个参数?

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

Is there a way to reuse an argument in fmt.Printf?

问题

我有一个情况,我想要在printf中重复使用我的参数。

  1. fmt.Printf("%d %d", i, i)

有没有办法告诉fmt.Printf只重用同一个i

  1. fmt.Printf("%d %d", i)
英文:

I have a situation where I want to use my printf argument twice.

  1. fmt.Printf("%d %d", i, i)

Is there a way to tell fmt.Printf to just reuse the same i?

  1. fmt.Printf("%d %d", i)

答案1

得分: 91

你可以使用[n]表示法来指定显式的参数索引,如下所示:

  1. fmt.Printf("%[1]d %[1]d\n", i)

这里有一个完整的示例供你尝试:http://play.golang.org/p/Sfaai-XgzN

英文:

You can use the [n] notation to specify explicit argument indexes like so:

  1. fmt.Printf("%[1]d %[1]d\n", i)

Here is a full example you can experiment with: http://play.golang.org/p/Sfaai-XgzN

答案2

得分: 2

另一个选项是text/template

  1. package main
  2. import (
  3. "strings"
  4. "text/template"
  5. )
  6. func format(s string, v interface{}) string {
  7. t, b := new(template.Template), new(strings.Builder)
  8. template.Must(t.Parse(s)).Execute(b, v)
  9. return b.String()
  10. }
  11. func main() {
  12. i := 999
  13. println(format("{{.}} {{.}}", i))
  14. }
英文:

Another option is text/template:

  1. package main
  2. import (
  3. "strings"
  4. "text/template"
  5. )
  6. func format(s string, v interface{}) string {
  7. t, b := new(template.Template), new(strings.Builder)
  8. template.Must(t.Parse(s)).Execute(b, v)
  9. return b.String()
  10. }
  11. func main() {
  12. i := 999
  13. println(format("{{.}} {{.}}", i))
  14. }

huangapple
  • 本文由 发表于 2014年10月29日 15:20:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/26624699.html
匿名

发表评论

匿名网友

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

确定