Sobes.tech
Senior

What happens if a function declares a variable of a struct type, assigns it nil through new, and returns an error interface?

sobes.tech AI

Answer from AI

If a function declares a variable of a struct type, allocates memory with new, and assigns it nil, then returns an error interface, the behavior depends on what exactly is returned.

In Go, an interface contains two fields: type and value. If an error interface variable is returned, which contains a pointer to a struct that is nil, then the interface will not be equal to nil because the type inside the interface is set.

Example:

func f() error {
    var s *MyStruct = new(MyStruct) // s points to allocated memory
    s = nil                         // now s is nil
    return s                        // returning s as error
}

func main() {
    err := f()
    if err == nil {
        fmt.Println("err is nil")
    } else {
        fmt.Println("err is NOT nil")
    }
}

In this example, err will be not equal to nil because the interface contains the type *MyStruct, but the value is nil. This is a common trap in Go.

To return a truly nil interface, you should return nil itself, for example:

return nil

and not a nil pointer.

In summary: if you return a nil pointer to a struct as an error, the interface will not be equal to nil, which can lead to unexpected behavior when checking for nil.