Go core
Browse topics

Nil interfaces

Version
1.27
Review
Draft

Summary#

An interface can hold a concrete type with a nil pointer as its value. Comparing that interface to nil returns false because its dynamic type is still present.

Syntax#

go
var pointer *Item
var value any = pointer
empty := value == nil

Example#

go
package main

import "fmt"

type item struct{}

func main() {
	var pointer *item
	var assigned any = pointer
	var empty any

	fmt.Println(pointer == nil)
	fmt.Println(assigned == nil)
	fmt.Println(empty == nil)
}

Expected output#

Text
true
false
true

Common mistakes#

A function returning error can accidentally wrap a nil pointer of a custom error type. Return nil explicitly on success. When an interface is documented to contain a particular pointer type, a type assertion lets you check that pointer for nil separately.

Version applicability#

Interface nil comparisons work this way from Go 1.0. The syntax and example require Go 1.18 for any. Use interface{} in older source.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0