Replace all variables in Sprintf with same variable

两盒软妹~` 提交于 2019-12-28 16:47:06

问题


Is it possible using fmt.Sprintf() to replace all variables in the formatted string with the same value?

Something like:

val := "foo"
s := fmt.Sprintf("%v in %v is %v", val)

which would return

"foo in foo is foo"

回答1:


It's possible, but the format string must be modified, you must use explicit argument indicies:

Explicit argument indexes:

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. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

Your example:

val := "foo"
s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
fmt.Println(s)

Output (try it on the Go Playground):

foo in foo is foo

Of course the above example can simply be written in one line:

fmt.Printf("%[1]v in %[1]v is %[1]v", "foo")

Also as a minor simplification, the first explicit argument index may be omitted as it defaults to 1:

fmt.Printf("%v in %[1]v is %[1]v", "foo")


来源:https://stackoverflow.com/questions/37001449/replace-all-variables-in-sprintf-with-same-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!