Consider following simplified example:
package main
import (
"fmt"
)
type IMessenger interface {
Message()
}
type TMyMessenger struct {
}
func (m TMyMessenger) Message() {}
func MessengerFactory() IMessenger {
return getInternalMessengerVariant()
}
func getInternalMessengerVariant() *TMyMessenger {
return nil
}
func main() {
e := MessengerFactory()
fmt.Println(" e == nil", e == nil) // *TMyMessenger(nil)
if e != nil {
e.Message()
}
}
And it's output:
e == nil false
panic: runtime error: invalid memory address or nil pointer dereference
Question 1:
Is there an idiomatic Go way to check if e points to a nil pointer?
Preferably an inline snippet.
Basically make the e != nil to be false even in the example case.
What I have considered:
There would not be this issue if
getInternalMessengerVariant()would return Interface type instead of concrete pointer, but it requires refactor and may still go undetected and yield itself as a panic at runtime (if e != nil).func getInternalMessengerVariant() IMessenger { return nil }Rewrite MessengerFactory() to intercept the internal returns:
func MessengerFactory() IMessenger { if m := getInternalMessengerVariant(); m != nil { return m } return nil }Be very specific on type checking, but what if there are many types:
if e != nil && e != (*TMyMessenger)(nil) { e.Message() }