Replace Individual Variables in Sprintf with Same Value
In fmt.Sprintf(), argument indexes can be specified explicitly using the notation [n], allowing different variables to be replaced at different positions in the formatted string. However, using this approach to replace all variables with the same value requires a slight modification to the format string.
Solution:
Instead of relying on successive arguments, use bracketed argument indexes before each formatting verb to indicate that the same argument should be used:
val := "foo" s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
This format string specifies that argument index 1 should be used for all three formatting verbs, resulting in:
"foo in foo is foo"
Simplified Options:
The first explicit argument index can be omitted, as it defaults to 1:
fmt.Printf("%v in %[1]v is %[1]v", "foo")
Additionally, the brackets and argument index can be combined into a single string:
fmt.Printf("%v in %1v is %1v", "foo")
Conclusion:
By using explicit argument indexes, it is possible to replace all variables in fmt.Sprintf() with the same value, providing greater flexibility in formatting strings.
The above is the detailed content of How Can I Replace All Variables in fmt.Sprintf() with the Same Value?. For more information, please follow other related articles on the PHP Chinese website!