Converting Nil Interface to Pointer of a Type in Golang
When attempting to convert a nil interface to a pointer of a specific type, an error occurs: "interface conversion: interface is nil". To understand why this fails, it's important to grasp the distinction between static and dynamic types.
Nexter is an interface, which specifies a static type. Variables of type Nexter can hold values of various dynamic types that implement the Nexter interface, such as *Node or other custom types. When a nil interface variable is assigned to a pointer variable, it's impossible to determine the actual dynamic type of the value it holds (since it holds none).
As a result, type assertion, which is typically used in the form x.(T) to assert that x is of type T and cast it to T, fails. This is because the spec of Go language explicitly states that x.(T) only works when x is not nil. Using type assertion on a nil interface variable will result in a runtime panic.
To achieve a similar effect to n = p.(*Node) but starting from a nil interface, the following approach can be used:
var p Nexter = (*Node)(nil)
An interface value actually holds a pair of (value, dynamic type). In this case, p is not nil but holds a pair of (nil, *Node). This allows type assertion on p to succeed.
Alternatively, to explicitly handle nil values, use the "comma-ok" form:
if n, ok := p.(*Node); ok { fmt.Printf("n=%#v\n", n) }
The "comma-ok" form ensures that no runtime panic occurs, and ok will be false if the assertion fails (i.e., p holds a nil value or a value of a different type).
The above is the detailed content of How Can I Safely Convert a Nil Interface to a Pointer in Go?. For more information, please follow other related articles on the PHP Chinese website!