I've tried to cast nil
(of type *MyError
) to error. By comparing the value of cast variable to nil, the result is different. Here is the code:
package main
import (
"fmt"
)
type MyError struct {
err error
}
func (e *MyError) Error() string {
return e.err.Error()
}
func nilErr() *MyError {
return nil
}
func main() {
e := nilErr()
fmt.Println(e) // <nil>
fmt.Println(error(e)) // <nil>
fmt.Printf("%#v\n", e) // (*main.MyError)(nil)
fmt.Printf("%#v\n", error(e)) // (*main.MyError)(nil)
fmt.Println(e == error(e)) // true
fmt.Println(e == nil) // true
fmt.Println(error(e) == nil) // false
}
playground: try code
The strange part is that the comparison of e
to error(e)
returns true
but comparing each of them to nil
gives different results.
Is there something wrong with the cast? If yes, How should it be done?