This question already has an answer here:
I have a situation where the value of a variable "err error" value can only be "nil" but asserts "( err == nil ) == false" once it has been reassigned.
Example code below:
package main
import (
"fmt"
"log"
)
type TestError struct {
Message string
}
func (e *TestError) Error() string {
return e.Message
}
func NewTestError(err error) *TestError {
if err == nil {
return nil
}
log.Printf("NewTestError( ... ): creating new NewTestError err = %s", err)
return &TestError{Message: err.Error()}
}
func main() {
var err error
_, err = fmt.Printf("excuse.
")
err = NewTestError(err)
log.Printf("main( ... ): err == nil. %v", (err == nil))
log.Printf("main( ... ): err = %#v", err)
}
I get the following output from the above code:
excuse.
2015/07/30 08:28:28 main( ... ): err == nil. false
2015/07/30 08:28:28 main( ... ): err = (*main.TestError)(nil)
How can those last two lines be output?
</div>
For an interface value (like an error
value) to compare equal to nil
, both the actual contained value and the actual contained type have to be nil
. In your case you have an interface value, which holds a nil
pointer, but a *TestError
(i.e. non-nil
) type.
PS. Just in case it's not clear what are these "interface values", you can check this http://research.swtch.com/interfaces
In the second case you're printing the interface instances information which is the type and the value, type being (*main.TestError)
value being (nil)
. In the first case what you're actually comparing isn't nil
because it's also the interface.