通过替换相同的子字符串来格式化字符串

This question already has an answer here:

I have a code which looks like:

const query = `select * 
               from %s.dbo.table1 
               join %s.dbo.table2
                 on ....
               join %s.dbo.table3
                 on ....
               join %s.dbo.table4
                 on ....`

 fmt.Sprintf(query, dbName, dbName, dbName, dbName)

I just create a SQL query by inserting the database name to all %s occurrences. Is the a better way to do it without repeating dbName ?

</div>

Use %[1]s:

const query = `select * 
           from %[1]s.dbo.table1 
           join %[1]s.dbo.table2
             on ....
           join %[1]s.dbo.table3
             on ....
           join %[1]s.dbo.table4
             on ....`
q := fmt.Sprintf(query, dbName)

Playground: https://play.golang.org/p/2DDiGfxLPk.

Documentation: https://golang.org/pkg/fmt/.

For example,

fmt.Sprintf("%[2]d %[1]d
", 11, 22)

will yield "22 11", while

fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)

equivalent to

fmt.Sprintf("%6.2f", 12.0)

will yield " 12.00". (…)