In conventional fmt.Sprintf() usage, variables are sequentially substituted into the formatted string. However, it is feasible to replicate a single variable throughout the string.
Utilizing explicit argument indexes, the format string can be modified to reference the same argument multiple times:
val := "foo" s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
The %[n] notation before a formatting verb specifies the index of the argument to be used. In this case, %[1] indicates that the first argument (val) should be used for all instances of the placeholder.
Executing the modified Sprintf:
fmt.Println(s)
Produces:
foo in foo is foo
Effectively, every variable placehold in the string is replaced with the value of val, resulting in the desired replication.
For the specific scenario where the first argument should be used consistently, the %[1] index can be omitted:
fmt.Sprintf("%v in %[1]v is %[1]v", "foo")
This abbreviated syntax simplifies the formatting string while still achieving the same replication functionality.
The above is the detailed content of How Can I Repeat a Variable in Go's fmt.Sprintf Using Argument Indexes?. For more information, please follow other related articles on the PHP Chinese website!