dream_high1026 2019-04-06 18:31
浏览 171

如何将pq.Int64Array转换为字符串?

In Golang application I make sql query to PostgreSQL database which return me array of int.

var identifiers [] pq.Int64Array

// Execute SQL query by "database/sql" package.
if err := database.DBSQL.QueryRow(sqlStatement.String()).Scan(&identifiers); err != nil {
    log.Println(err)
    utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
    return
}

How convert identifiers array with pq.Int64Array elements to string where elements of array separated by comma?

  • 写回答

1条回答 默认 最新

  • douduan5086 2019-04-06 18:38
    关注

    Because the type pq.Int64Array is a slice type, the application is scanning to a slice of slices. Scan to a slice only:

    var identifiers pq.Int64Array
    if err := database.DBSQL.QueryRow(sqlStatement.String()).Scan(&identifiers); err != nil {
        log.Println(err)
        utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
        return
    }
    

    Convert each id to a string and append to a buffer. Insert separators between each id. Convert the buffer to a string when done.

    var buf []byte
    for i, id := range identifiers {
        if i > 0 {
            buf = append(buf, ',')
        }
        buf = strconv.AppendInt(buf, int64(id), 10)
    }
    s := string(buf)
    
    评论

报告相同问题?