-1

Can someone explain this go code to me?
When this is invoked, the err != nil returns true, thus leading to a nil pointer reference.

type E struct{}

func (e E) Error() string {
    return ""
}

func DoStuff() *E {
    return nil
}

func main() {
    var err *E
    err = DoStuff()
    log.Println(err) // nil
    testErr(err)
}

func testErr(err error) {
    if err != nil {
        log.Println("got error", err.Error())
    }
}

https://play.golang.org/p/iys7U_UMhG

I have understood that this has something to do with the fact that I am dealing with a nil-struct-pointer casted to an interface...

However I am confused how to design this interface DoStuff, if one wants to return a "smart" error object, not just plain error.

cfstras
  • 1,613
  • 15
  • 21

1 Answers1

0

You were on the right track. Thing is that you are returning pointer to struct and your Error method is implemented with non-pointer caller.

Following should work (I only added * for receiver of Error method:

package main

import "log"

type E struct{}

func (e *E) Error() string {
    return ""
}

func DoStuff() *E {
    return nil
}

func main() {
    var err *E
    err = DoStuff()
    log.Println(err) // nil
    testErr(err)
}

func testErr(err error) {
    if err != nil {
        log.Println("got error", err.Error())
    }
}
del-boy
  • 3,556
  • 3
  • 26
  • 39
  • While this does not crash, it still echoes "got error" -- even though the error value passed is actually nil? – cfstras Oct 20 '16 at 09:23