Go interfaces and nil
This little subtlety in Go caught me today. I was trying determine if what an interface referenced was nil and I wrote a bit of code like this (this is not the actual code I wrote, just a simple version to demonstrate the issue):
type I interface {
}
func main() {
var p *int
var i I
i = p
if i != nil {
fmt.Println("p + 1 ==", *i.(*int) + 1)
}
}
Sadly, it did not have the intended outcome and the program panicked:
panic: runtime error: invalid memory address or nil pointer dereference
What happened? I tested to see if the interface was nil but the program still panicked over a nil pointer? That can't be right. So I wrote a small test program and realized something pretty simple. You need to test both that the interface isn't nil and also check to make sure that what it references isn't nil:
type I interface {
}
func main() {
var p *int
var i I
i = p
if i != nil && i.(*int) != nil {
fmt.Println("p + 1 ==", *i.(*int) + 1)
}
}
I've been writing Go for over a year and I'd never really thought about this before.. or been caught by a defect because of it.
No comments:
Post a Comment