douhao123457
2018-10-27 22:09
浏览 300
已采纳

在fmt.Sprintf格式字符串中多次引用相同的参数

I have this function:

func getTableCreationCommands(v string) string {
    return `
        CREATE TABLE share_` + v + ` PARTITION OF share FOR VALUES IN (` + v + `);
        CREATE TABLE nearby_` + v + ` PARTITION OF nearby FOR VALUES IN (` + v + `);
    `
}

It's a little wonky... is there a way to format the string using fmt.Sprintf?

Something like this:

func getTableCreationCommands(v string) string {
    return fmt.Sprintf(`
        CREATE TABLE share_%v PARTITION OF share FOR VALUES IN (%v);
        CREATE TABLE nearby_%v PARTITION OF nearby FOR VALUES IN (%v);
    `, v, v, v, v)
}

but without the need to pass v 4 times?

图片转代码服务由CSDN问答提供 功能建议

我具有以下功能:

  func getTableCreationCommands(v字符串 )字符串{
返回`
 CREATE TABLE share_` + v +`为价值IN分配的份额(`+ v +`); 
 CREATE TABLE near__ + v +`附近FOR VALUES IN的份额的((+  v +`); 
`
} 
   
 
 

有点奇怪...有一种方法可以使用 fmt.Sprintf格式化字符串

类似这样的东西:

  func getTableCreationCommands(v string)string {
 return fmt.Sprintf(`  
创建表share_%v共享价值份额(%v); 
创建表near_%v附近共享价值份额(%v); 
`,v,v,v,v)
  } 
   
 
 

但不需要通过 v 4次?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douna2633 2018-10-27 22:26
    已采纳

    Package fmt

    import "fmt" 
    

    Explicit argument indexes:

    In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead.


    You can pass the variable v once. For example,

    package main
    
    import "fmt"
    
    func getTableCreationCommands(v 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);
        `, v)
    }
    
    func main() {
        fmt.Println(getTableCreationCommands(("X")))
    }
    

    Playground: https://play.golang.org/p/DlafU_R_phq

    Output:

    CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
    CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题