0

Why c is not print while it's value is nil

Am I misunderstand something?

package main

import "fmt"

type MyError struct {
    Why string
    What string
}

func (this *MyError) Error() string {
    return this.What + this.Why
}

func main() {
    nilError := error(nil)
    if nilError == nil {
        fmt.Println("a")
    }
    if NilMyError() == nil {
        fmt.Println("b")
    }   
    if NilErrorFromMyError() == nil {
        fmt.Println("c")
    }
}

func NilErrorFromMyError() error {
    return NilMyError()
}

func NilMyError() *MyError {
    return nil
}

Result :

a
b
kitta
  • 1,723
  • 3
  • 23
  • 33
  • 2
    `NilMyError()` returns a `nil` pointer. `NilErrorFromMyError()` returns this `nil` value, but before it does, an implicit interface value of type `error` is created because `*MyError` is a concrete type and `error` is an interface type. This is where your `nil` value "gets" lost: a non-`nil` interface value will be created holding a `nil` value and `*MyError` type. Read the duplicate-marked answer for greater detail. – icza Dec 17 '15 at 19:44
  • Hey, check out [my answer](http://stackoverflow.com/a/34343388/230340) explaining exactly this problem. Hope I helped. – Zippo Dec 17 '15 at 20:15
  • This is [explained in the Go Language FAQ](https://golang.org/doc/faq#nil_error). – Charlie Tumahai Dec 18 '15 at 02:04

0 Answers0