Interface as Void Pointer in Go
In data structure libraries, it's often desirable to work with different data types. In C, this can be done using void pointers. However, in Go, void pointers aren't available.
The Go Solution: Interface{}
The Go equivalent of a void pointer is the empty interface, interface{}. According to the language specification, "all types implement the empty interface." This means that any type can be stored in a variable of type interface{}.
Usage Example
To use interface{}, simply declare a variable of that type:
var v interface{}
You can then assign any data type to the variable:
v = 10
The data can then be retrieved using type assertions:
if number, ok := v.(int); ok { // v can be safely treated as an int }
The above is the detailed content of How Does Go Handle Void Pointers Using `interface{}`?. For more information, please follow other related articles on the PHP Chinese website!