尝试在Go中扫描到int64指针时出现错误

I'm getting this error

 Scan error on column index 1: converting string "<nil>" to a int64:
 strconv.ParseInt: parsing "<nil>": invalid syntax

when trying to run this simple code:

var id int64
var replyTo *int64
replyTo = new(int64)

query := `
    SELECT id, reply_to
    FROM message
    WHERE id = 211
    LIMIT 1;
`
if err := sql.DB.QueryRow(query).Scan(&id, replyTo); err != nil {
    log.Println(err)
}

spew.Dump(id, replyTo)

The table I am selecting from looks like this:

enter image description here

If I change the select query to: WHERE id = 210, instead of 211 then it works.

The sql.DB is just an instance of the sqlx library.

var DB *sqlx.DB

I am using a pointer to be able to catch NULL columns from the database. I am using a pointer because I am not sure if sql.NullInt64 works well with the sqlx library.

Why do I get this error? What can I do about it?

Scan needs a pointer to your pointer for this to work :

var id int64
var replyTo *int64
replyTo = new(int64)

query := `
    SELECT id, reply_to
    FROM message
    WHERE id = 211
    LIMIT 1;
`
// The change is here : &replyTo instead of just replyTo
if err := sql.DB.QueryRow(query).Scan(&id, &replyTo); err != nil {
    log.Println(err)
}

spew.Dump(id, replyTo)

Then don't forget to test for replyTo == nil before using the value *replyTo

Alternative solution : use a sql.NullInt64 : https://golang.org/pkg/database/sql/#NullInt64