Assigning nil value to driver.Value makes driver.Value not equal nil

Issue

After assigning a nil value to a driver.Value variable, the variable does not equal nil.

package main

import (
    "database/sql/driver"
    "fmt"
)

func main() {
    var dv driver.Value
    dv = nil
    if dv == nil {
        fmt.Println("driver.Value nil")
    }
    var b []byte
    if b == nil {
        fmt.Println("byte slice nil")
    }
    dv = b
    if dv == nil {
        fmt.Println("driver.Value nil")
    }
}

Output:

driver.Value nil
byte slice nil

Playground: https://play.golang.org/p/oTweLQLA8Qj

Why is that the case?

Solution

driver.Value is an interface. Go interfaces contain two values: a type and a pointer to the underlying value. An interface is nil if both of those are nil.

In your case, after

dv = b

where b is a nil []byte, the interface dv has type []byte with value nil. So the interface itself is not nil.

https://golang.org/doc/faq#nil_error

Answered By – Burak Serdar

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.