how to split long lines for fmt.sprintf

15.5k views Asked by At

I have a very long line in fmt.Sprintf. How do I split it in the code? I don't want to put everything in a single line so the code looks ugly.

fmt.Sprintf("a:%s, b:%s  ...... this goes really long")
5

There are 5 answers

0
Zombo On

Another option is strings.Builder:

package main

import (
   "fmt"
   "strings"
)

func main() {
   b := new(strings.Builder)
   fmt.Fprint(b, "North")
   fmt.Fprint(b, "South")
   println(b.String() == "NorthSouth")
}

https://golang.org/pkg/strings#Builder

0
Cerise Limón On

Use string concatenation to construct a single string value on multiple lines:

 fmt.Sprintf("a:%s, b:%s " +
    " ...... this goes really long",
    s1, s2)

The long string in this example is built at compile time because the string concatenation is a constant expression.

You can split the string at contained newlines using a raw string literal:

     fmt.Sprintf(`this text is on the first line
and this text is on the second line,
and third`)
0
Paulo On

Why don't you split it out:

fmt.Sprintf("a:%s, b:%s ", x1, x2)

fmt.Sprintf("...... ")

fmt.Sprintf("this goes really long")

Or you can split them out with the plus sign as indicated by MuffinTop.

2
evanmcdonnal On

Since you're using Sprintf already (meaning you'll have a string like "this is the string with %s placeholders in it") you could just add more place holders to the string and then put the values you'd like there on their own lines like;

fmt.Sprintf("This %s is so long that I need %s%s%s for the other three strings,
"string",
"some super long statement that I don't want to type on 50 lines",
"another one of those",
"yet another one of those")

Another option is just to use string concatenation like "string 1" + "string 2".

0
Kyle Heuton On

You can also use raw string literals inside backticks, like this:

columns := "id, name"
table := "users"
query := fmt.Sprintf(`
    SELECT %s
    FROM %s
  `, columns, table)
fmt.Println(query)

There are a few caveats to this approach:

  1. Raw strings don't parse escape sequences
  2. All the whitespace will be preserved, so there will be a newline and then several tabs before the FROM clause in this query.

These problems can be a challenge for some, and the whitespace will produce some ugly resulting strings. However, I prefer this approach as it allows you to copy and paste long, complex SQL queries outside of your code and into other contexts, like sql worksheets for testing.