Sorry, it's a method not a property, but I think my point remains valid with regards to the example in that article. Just to be clear, I'm not trying to defend nil here, but I do think it's important to understand the issue because I think the authors code would have failed regardless of the language. So Let's break the code down: first they create a struct exposed via an interface{}
type T struct{}
func (t T) F() {}
type P interface {
F()
}
func newT() *T { return new(T) }Then they create an initialized variable that object type:
t := newT()
t2 := t
...and set that interface{} to nil: if !ENABLE_FEATURE {
t2 = nil
}
Then they check the value returned from a method of the struct - bare in mind this is after the struct has been `nil`ed: thing := factory(t2)
fmt.Println(thing.P == nil) // returns nil
If there's a likelihood that they could be working with nil interfaces then they should be first checking the value of the interface before checking the value of the methods within it. Most OOP languages would raise an exception / print runtime error (in the case of JIT dynamic languages) or downright crash if you tried to access methods or properties of a nil / null / whatever type. So I'm not defending Go's behavior but their example is peculiar to say the least.That all said, I do feel your examples are a lot more relevant to this discussion than the one that prompted the discussion to begin with.