Home >Backend Development >Golang >How to Safely Convert Nil Interfaces to Pointers in Go?
Converting Null Interfaces to Pointers in Go
In Go, converting a nil interface to a pointer of a specific type can result in an error. In the sample code provided:
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) // prints true n = p.(*Node) // fails }
This fails because a static interface (Nexter) can hold values of different dynamic types, including nil. Type assertion (p.(*Node)) cannot be performed on a nil interface value.
However, it is possible to directly assign a nil value to a pointer of a specific type:
n = (*Node)(nil)
This assigns a nil value with the dynamic type *Node to n.
To handle nil interface values, you can check them explicitly:
if p != nil { n = p.(*Node) // only succeeds if p contains a value of type *Node }
Alternatively, use the "comma-ok" form:
if n, ok := p.(*Node); ok { // n is not nil and holds a value of type *Node }
Using the "comma-ok" form ensures that the assertion never fails and returns a boolean indicating whether the assertion holds instead of causing a panic. This allows you to safely handle both nil and non-nil interface values.
The above is the detailed content of How to Safely Convert Nil Interfaces to Pointers in Go?. For more information, please follow other related articles on the PHP Chinese website!