Home >Backend Development >Golang >How to Safely Convert a Nil Interface to a Pointer in Go?
Nil Interface to Pointer Conversion Error in GoLang
In GoLang, attempting to convert a nil interface to a pointer of a specific type, as illustrated below, triggers an error:
type Nexter interface { Next() Nexter } type Node struct { next Nexter } func (n *Node) Next() Nexter {...} func main() { var p Nexter var n *Node fmt.Println(n == nil) // true n = p.(*Node) // error }
This error occurs because a static-type variable of interface type (e.g., Nexter) can hold values of various dynamic types, including nil. While it's possible to convert a nil value to a pointer using (*Node)(nil), type assertion as used in the example cannot be applied because:
x.(T)
requires x to be non-nil and of type T. In this case, p may contain values of various types or nil.
Instead, explicit checks can be employed:
if p != nil { n = p.(*Node) // succeeds if p contains a *Node value }
Alternatively, the "comma-ok" form provides a safer option:
if n, ok := p.(*Node); ok { fmt.Printf("n=%#v\n", n) }
Using the "comma-ok" form allows handling of both nil and non-nil interface values without triggering a panic.
The above is the detailed content of How to Safely Convert a Nil Interface to a Pointer in Go?. For more information, please follow other related articles on the PHP Chinese website!