0

I try to scan a boolean result into a boolean pointer:

var expired bool
db.QueryRow(context.Background(), sql, id, n).Scan(&expired)

The code fails with the following error:

can't scan into dest[0]: cannot scan NULL into *bool

Which Go type do I have to use to scan a SQL boolean, which can be true, false and NULL?

ceving
  • 21,900
  • 13
  • 104
  • 178
  • 1
    Use a pointer (e.g. `var expired *bool`) or a custom type ([pgx](https://pkg.go.dev/github.com/jackc/pgx/v5@v5.4.0/pgtype#hdr-Null_Values), [stdlib](https://pkg.go.dev/database/sql#NullBool)). The [pgx docs](https://pkg.go.dev/github.com/jackc/pgx#hdr-Null_Mapping) have more info (or see [this question](https://stackoverflow.com/q/26976251/11810946) or [this question](https://stackoverflow.com/q/28642838/11810946)). – Brits Jun 14 '23 at 20:26

1 Answers1

3

My preference is using a pointer for bool

var expired *bool
db.QueryRow(context.Background(), sql, id, n).Scan(&expired)

As bool only have false and true values, it does not provide a way to represent NULL.

sql.NullBool is alse a good choice.

FLAGLORD
  • 93
  • 4