Typed Nil In Interfaces Is Not Nil
An interface holding a nil pointer is not a nil interface: it still carries the concrete type, so == nil lies while method calls still dispatch.
Code
package main
import "fmt"
type Store interface {
Get(key string) string
}
type dbStore struct {
data map[string]string
}
// Get 不解引用指针:nil 接收者照样能调用,返回零值
func (s *dbStore) Get(key string) string {
if s == nil {
return ""
}
return s.data[key]
}
func main() {
var s *dbStore // 具体指针是 nil
var store Store = s // 装进 interface 后携带了类型信息:typed nil
fmt.Println("pointer nil:", s == nil)
fmt.Println("interface nil:", store == nil) // false:== nil 会误判
fmt.Printf("Get on typed nil: %q\n", store.Get("k")) // 照常派发,不 panic
var absent Store // 真正的 nil interface:类型与值都为空
fmt.Println("zero interface nil:", absent == nil)
}What the code does
Count the functions Get and main as the entire surface area of Typed Nil In Interfaces Is Not Nil.
Applying it
Entry signature: func (s *dbStore) Get(key string) string
Output lines are prefixed (pointer nil:, interface nil:, Get on typed nil:), so each printed result points back to the step that made it.
The demo flow inside main is Get — run the file to see it end to end.
Statements that matter
func (s *dbStore) Get(key string) string {
if s == nil {
return ""
}
return s.data[key]
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Typed Nil In Interfaces Is Not Nil print when run?
- Invoke the file as-is — the `pointer nil:`, `interface nil:`, `Get on typed nil:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.