-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.

0

1 Answer 1

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())
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

While this does not crash, it still echoes "got error" -- even though the error value passed is actually nil?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.