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")
The Split() method in Golang (defined in the strings library) breaks a string down into a list of substrings using a specified separator.
Creating a multiline string in Go is actually incredibly easy. Simply use the backtick ( ` ) character when declaring or assigning your string value. str := `This is a multiline string.
The fmt. Sprintf function in the GO programming language is a function used to return a formatted string. fmt. Sprintf supports custom format specifiers and uses a format string to generate the final output string.
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`)
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With