Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for long string literals in Go

I've got a long string literal in Go:

db.Exec("UPDATE mytable SET (I, Have, Lots, Of, Fields) = ('suchalongvalue', 'thisislongaswell', 'ohmansolong', 'wowsolong', 'loooooooooooooooooooooooooong')")

I see two ways to make this more manageable: raw quotes, or multiple concatenated quotes:

db.Exec(`UPDATE mytable SET (I, Have, Lots, Of, Fields) 
         = ('suchalongvalue', 'thisislongaswell', 'ohmansolong', 
            'wowsolong', 'loooooooooooooooooooooooooong')`)

db.Exec("UPDATE mytable SET (I, Have, Lots, Of, Fields) = " + 
    "('suchalongvalue', 'thisislongaswell', 'ohmansolong', " +
    "'wowsolong', 'loooooooooooooooooooooooooong')")

The first feels more right, but the preceding spaces will be included in the string, making the resulting string have awkward runs of spaces in it. Is either of these considered idiomatic Go?

like image 243
joshlf Avatar asked Jan 05 '14 22:01

joshlf


People also ask

How many string literals are used in Go programming?

Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals). The zero values of string types are blank strings, which can be represented with "" or `` in literal.

How do you write multi line string in Golang?

Multiline strings 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.


3 Answers

This is what I do:

q := `UPDATE mytable SET (I, Have, Lots, Of, Fields) = ` +
     `('suchalongvalue', ` + 
     `'thisislongaswell', ` +
     `'wowsolong', ` + 
     `loooooooooooooooooooooooooong')`

db.Exec(q)

I think it looks a lot cleaner

like image 174
Sebastian Macias Avatar answered Oct 18 '22 03:10

Sebastian Macias


It looks weird putting the long string literal in the parameter like that. I would prefer:

const updateQuery=`
UPDATE mytable SET (I, Have, Lots, Of, Fields) 
= ('suchalongvalue', 'thisislongaswell', 'ohmansolong', 
'wowsolong', 'loooooooooooooooooooooooooong')`

func doUpdate(){
  db.Exec(updateQuery)
}

I also prefer a single newline at the beginning to the odd spaces in each line. That way you can kill it with strings.Trim if it causes problems.

like image 43
captncraig Avatar answered Oct 18 '22 03:10

captncraig


You could do:

s := `UPDATE mytable SET (I, Have, Lots, Of, Fields) = `
s += `('suchalongvalue', `
s += `'thisislongaswell', `
s += `'wowsolong', `
s += `loooooooooooooooooooooooooong')`

db.Exec(s)
like image 2
Sebastian Bartos Avatar answered Oct 18 '22 01:10

Sebastian Bartos