Home > Backend Development > Golang > How to Safely Convert a Nil Interface to a Pointer in Go?

How to Safely Convert a Nil Interface to a Pointer in Go?

DDD
Release: 2024-12-19 14:01:16
Original
195 people have browsed it

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

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

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

Alternatively, the "comma-ok" form provides a safer option:

if n, ok := p.(*Node); ok {
    fmt.Printf("n=%#v\n", n)
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template