dongpu1908 2017-08-28 13:03
浏览 6
已采纳

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

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>
  • 写回答

1条回答 默认 最新

  • dongzhou1901 2017-08-28 13:16
    关注

    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". (…)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line