Referencing Parameters Multiple Times in fmt.Sprintf Format Strings
In your code, you have a function that creates table creation commands using fmt.Sprintf. You want to avoid passing the same parameter multiple times.
Solution using Explicit Argument Indexing
According to the documentation for fmt.Printf and related functions, you can use explicit argument indexes to format the nth argument:
func getTableCreationCommands(s string) string { return fmt.Sprintf(` CREATE TABLE share_%[1]v PARTITION OF share FOR VALUES IN (%[1]v); CREATE TABLE nearby_%[1]v PARTITION OF nearby FOR VALUES IN (%[1]v); `, s) }
In the format string, %[1]v refers to the first argument, s.
Example
Here's an example using this approach:
package main import "fmt" func getTableCreationCommands(s string) string { return fmt.Sprintf(` CREATE TABLE share_%[1]v PARTITION OF share FOR VALUES IN (%[1]v); CREATE TABLE nearby_%[1]v PARTITION OF nearby FOR VALUES IN (%[1]v); `, s) } func main() { fmt.Println(getTableCreationCommands("X")) }
Output:
CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X); CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);
By using explicit argument indexes, you can reference the same parameter multiple times without passing it separately.
The above is the detailed content of How can I reference parameters multiple times in fmt.Sprintf format strings?. For more information, please follow other related articles on the PHP Chinese website!