Home > Backend Development > Golang > How to Safely Convert Nil Interfaces to Pointers in Go?

How to Safely Convert Nil Interfaces to Pointers in Go?

Barbara Streisand
Release: 2024-12-04 08:01:12
Original
263 people have browsed it

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
}
Copy after login

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)
Copy after login

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
}
Copy after login

Alternatively, use the "comma-ok" form:

if n, ok := p.(*Node); ok {
    // n is not nil and holds a value of type *Node
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template