Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split long lines for fmt.sprintf

Tags:

go

gofmt

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")
like image 604
WhatABeautifulWorld Avatar asked Feb 01 '16 23:02

WhatABeautifulWorld


People also ask

How do you break a long string in Golang?

The Split() method​ in Golang (defined in the strings library) breaks a string down into a list of substrings using a specified separator.

How do you print multiple lines in go?

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.

What does fmt sprintf do?

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.


2 Answers

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`)
like image 198
Bayta Darell Avatar answered Oct 04 '22 17:10

Bayta Darell


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.

like image 45
Kyle Heuton Avatar answered Oct 04 '22 17:10

Kyle Heuton