How to split long lines for fmt.sprintf

I have a very long line in fmt.Sprintf. How to break it in code? I don't want to put everything on one line, so the code looks ugly.

fmt.Sprintf("a:%s, b:%s ...... this goes really long") 
+5
source share
4 answers

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

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

You can split the string into the given newline strings using the string literal of the string :

  fmt.Sprintf(`this text is on the first line and this text is on the second line, and third`) 
+9
source

Since you are already using Sprintf (this means that you will have a line like “this is a line with placeholders% s in it”), you can simply add more place owners to the line and then put the values ​​that 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 to simply use string concatenation, for example "string 1" + "string 2" .

+2
source

Why don't you split it:

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

Or you can separate them with a plus sign, as indicated by MuffinTop.

+1
source

You can also use raw string literals inside backticks, for example:

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

There are a few caveats for this approach:

  • Raw strings do not parse escape sequences
  • All spaces will be saved, so in the FROM in this request there will be a new line and then several tabs.

These problems can be a problem for some, and spaces will lead to some ugly result lines. 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, for example, to sql tables for testing.

0
source

Source: https://habr.com/ru/post/1242057/


All Articles