Home >Backend Development >Golang >How Can I Repeat a Single Variable Across Multiple Placeholders in Go's fmt.Sprintf()?
Replicating Variable Values in Formatted Strings Using Sprintf
In Go, fmt.Sprintf() allows for the formatting of strings using placeholders that are substituted with the provided values. While it typically assigns each placeholder a unique value, it's often desirable to replace all placeholders with the same variable.
Explicit Argument Indexing
To achieve this, fmt.Sprintf() utilizes explicit argument indexing. Within the format string, placing [n] before a formatting verb ensures that the nth argument (indexed from 1) is formatted instead of the default ascending sequence. Similarly, [n] placed before a * for width or precision indicates the argument holding the specified value.
Example Usage
Consider the example provided in the question:
val := "foo" s := fmt.Sprintf("%v in %v is %v", val)
To replicate the val variable across all placeholders, modify the format string as follows:
s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
This results in the desired output:
"foo in foo is foo"
Simplified Notation
Note that the first explicit argument index can be omitted as it defaults to 1:
s := fmt.Sprintf("%v in %[1]v is %[1]v", val)
Conclusion
By leveraging explicit argument indexing, fmt.Sprintf() can be utilized to replicate a single variable value across all placeholders in a formatted string, providing a concise and efficient solution for specific scenarios.
The above is the detailed content of How Can I Repeat a Single Variable Across Multiple Placeholders in Go's fmt.Sprintf()?. For more information, please follow other related articles on the PHP Chinese website!