Why is it permissible to set the <nil> type of interface in Go?
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 it nildoes not Yell(), however, the program starts 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 nildoes the compiler consider it legal to assign to an interface?
Also from Go-docs:
An interface type variable can hold a value of any type with a set of methods, which is any superset of an interface.
How does "nil" contain a set of methods, which is a superset TesterInterface? The docs say that
The value of an uninitialized interface type variable is nil.
But this seems to contradict the first statement.
, , " ..." , , , nil. : , Go , .
, , nil . :
func Something() error {
...
return nil
}
, nil error. , . nil , nil? , nil - .
. nil error ? , , (nil, nil).
, , " nil" (.. a nil ) , , ? , , nil, nil - , nil -check . , nil, , (, return "no error" ).
( . " nil error ?", , , , , . , .)
@newacct , .
PeterSO . . , nil?