Go中长字符串文字的最佳实践

时间:2014-01-05 22:43:25

标签: string go literals idioms

我在Go中有一个很长的字符串文字:

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')`)

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

第一个感觉更正确,但前面的空格将包含在字符串中,使得结果字符串中的空格运行笨拙。这些都被认为是惯用的Go吗?

5 个答案:

答案 0 :(得分:4)

将长字符串文字放在参数中看起来很奇怪。我更喜欢:

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

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

我也更喜欢开头的一个换行符到每一行的奇数空格。这样,如果它导致问题,您可以使用strings.Trim将其终止。

答案 1 :(得分:1)

你可以这样做:

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

db.Exec(s)

答案 2 :(得分:1)

这就是我的所作所为:

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

db.Exec(q)

我觉得它看起来更干净

答案 3 :(得分:1)

因为我们在这个例子中谈论SQL ......

很少将字符串文字作为UPDATE_, err := db.Exec( `UPDATE mytable SET (I, Have, Lots, Of, Fields) = ($1, $2, $3, $4, $5)`, "suchalongvalue", "thisislongaswell", "ohmansolong", "wowsolong", "loooooooooooooooooooooooooong") 中的列值传递。您几乎总是从代码中传递计算值,在这种情况下,使用参数化查询要好得多。在编译时确实知道值的罕见情况下,参数化通常仍然是正确的答案:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    Boolean isSilent;
    String Silent = "";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        try {
            Bundle bundle = new Bundle();
            for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
                bundle.putString(entry.getKey(), entry.getValue());
                Log.d(entry.getKey(), entry.getValue());
            }
//            remoteMessage.getData().get("screen_id")
            if (remoteMessage.getData().size() > 0) {
                sendNotificationData(bundle.getString("data_title"), bundle.getString("data_body"), bundle.getString("screen_id"));

            } else if (remoteMessage.getNotification() != null) {
                sendNotification(remoteMessage.getNotification(), bundle.getString("screen_id"));
            }


        } catch (Exception ex) {
            ex.printStackTrace();

        }
    }

    private void sendNotification(RemoteMessage.Notification notificationR, String screenId) {
        NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intentNotification = new Intent(this, MainActivity.class);
        intentNotification.putExtra("screen_id", screenId);
        Log.v("sendNotification ", " >>>>>####>>>>>>>>  " + screenId);
        // finish previous activity
        if (!Silent.equals("yes")) {
            intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
                    .setContentTitle(notificationR.getTitle())
                    .setContentText(notificationR.getBody())
                    .setSmallIcon(getNotificationIcon())
                    .setLargeIcon(icon(getApplicationContext()))
                    .setLights(Color.LTGRAY, 1000, 1000)
                    .setAutoCancel(true)
                    .setTicker(notificationR.getTitle())
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));


            Notification notification = notificationBuilder.build();
            //  '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
            notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;

            nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);

        }
    }


    private void sendNotificationData(String dataTitle, String dataBody, String screenId) {
        NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intentNotification = new Intent(this, MainActivity.class);
        intentNotification.putExtra("screen_id", screenId);


        if (!Silent.equals("yes")) {
            intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
                    .setContentTitle(dataTitle)
                    .setContentText(dataBody)
                    .setSmallIcon(getNotificationIcon())
                    .setLargeIcon(icon(getApplicationContext()))
                    .setLights(Color.LTGRAY, 1000, 1000)
                    .setAutoCancel(true)
                    .setTicker(dataTitle)
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

            Notification notification = notificationBuilder.build();
            //  '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
            notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;

            nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);
        }
       @Override
        public boolean zzE(Intent intent) {
            isSilent = intent.hasExtra("silent");
            if (isSilent) {
                Silent = "yes";
            }
            return super.zzE(intent);
        }

答案 4 :(得分:0)

我更喜欢:

var updateStatement = `
    UPDATE
        mytable
    SET
        I = 'suchalongvalue'
        ,Have = 'thisislongaswell'
        ,Lots = 'ohmansolong'
        ,Of = 'wowsolong'
        ,Fields = 'loooooooooooooooooooooooooong'
`
func update(updateStatement string) {
    db.Exec(updateStatement)
}

应该看起来更干净。至少那是教给我的。