且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Go中的长字符串文字的***做法

更新时间:2023-11-06 22:10:04

看起来很奇怪,把长字符串文字放在参数中。我宁愿:

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

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

我也更喜欢单行换行到奇数行每行中有空格。这样,如果它导致问题,你可以用 strings.Trim 来杀死它。


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?

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.