Difference between *string and sql.NullString

go

Solution

SQL has different null values than Golang.

If you look at the definition of `sql.NullString` then this is what you get:

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}

As you can see, `sql.NullString` is a way to represent null string coming from SQL (which correspond to "NULL"). On the other hand, a nil `*string` is a pointer to a string which is nil, so the two are different.

Problem

I've been strugguling with SQL NULL values in Golang recently. After trying to unsuccessfully unmarshal JSON objects using `Decode()` and `sql.NullString`, I came to this answer on StackOverflow : Assigning null to JSON fields instead of empty strings in Golang The solution using a string pointer seems to work perfectly with Decode() and nil values. So what is the difference between `sql.NullString` and `*string` ? Is it just about nil checking ?

Original source

Related problems