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?
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)