http://play.golang.org/p/_GP3RZTh4Q
package main
import "fmt"
type TesterInterface interface{
Yell()
}
type Tester struct{}
func (t Tester) Yell() {
fmt.Println("HELLO")
}
func main() {
var t TesterInterface
t = Tester{}
t.Yell()
t = nil
t.Yell()
}
I would expect the compiler to complain about line 19 (t = nil
), since nil
doesn't implement Yell()
, however the program runs and provides the following output:
HELLO
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0xffffffff addr=0x0 pc=0x201a9]
goroutine 1 [running]:
runtime.panic(0xef060, 0x1b3d44)
/tmp/sandbox/go/src/pkg/runtime/panic.c:266 +0xe0
runtime.panicstring(0x1b3d44, 0x1b85)
/tmp/sandbox/go/src/pkg/runtime/panic.c:489 +0x120
runtime.sigpanic()
/tmp/sandbox/go/src/pkg/runtime/os_nacl.c:254 +0x80
main.main()
/tmpfs/gosandbox-229cdcdf_329829af_705be907_f12cf4dc_ed51e32e/prog.go:20 +0xa9
runtime.main()
/tmp/sandbox/go/src/pkg/runtime/proc.c:220 +0x1c0
runtime.goexit()
/tmp/sandbox/go/src/pkg/runtime/proc.c:1394
goroutine 2 [syscall]:
runtime.notetsleepg(0xfeefdf88, 0x0, 0xf8475800, 0xd)
/tmp/sandbox/go/src/pkg/runtime/lock_sema.c:254 +0xa0
runtime.MHeap_Scavenger()
/tmp/sandbox/go/src/pkg/runtime/mheap.c:463 +0xc0
runtime.goexit()
/tmp/sandbox/go/src/pkg/runtime/proc.c:1394
created by runtime.main
/tmp/sandbox/go/src/pkg/runtime/proc.c:179
[process exited with non-zero status]
Program exited.
Why does the compiler consider it legal to assign nil
to an interface?
Additionally, from the Go-docs:
A variable of interface type can store a value of any type with a method set that is any superset of the interface.
How does "nil" contain a method set that is a superset of TesterInterface
? The docs go on to say that
The value of an uninitialized variable of interface type is nil.
But this seems to contradict the first statement.