Understanding logic behind failing nil check

66 views
Skip to first unread message

Kevin

unread,
Nov 21, 2019, 10:33:49 AM11/21/19
to golang-nuts
hi all,
Im relatively new to go (but been a developer for over 15yrs) and wrote some code like this and it perplexed me for a couple hours.
```
var _ error = &Error{}
type Error struct{ message string }
func (e *Error) Error() string { return e.message }
func call1() error  { return call2() }
func call2() *Error { return nil }
func Test_Gotcha(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Errorf("Failed with a panic for null usage")
}
}()
err := call1()
if err != nil {
anError, ok := err.(*Error)
if ok {
fmt.Printf("this panics on nil reference %s\n", anError.message)
}
}
}
```
Im wondering what the logic is behind the `err!=nil` not catching the `<*Error> nil`  returned from call1?
Go seems straight pretty easy and straight forward most of the time but this seems to me a little odd.
PS Im using go 13.1

Ian Cottrell

unread,
Nov 21, 2019, 11:01:13 AM11/21/19
to Kevin, golang-nuts
Because the return of call1 is not nil, you gave it a proper type before you packed it into the error interface.
see https://golang.org/doc/faq#nil_error for an explanation. This bites most go programmers at least once.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/43021ee4-ce3c-4657-adcc-3a2c3aa6a859%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages