Home >Backend Development >Golang >How Can I Achieve the Functionality of a C Void Pointer in Go?
In C programming, a void pointer allows one to access memory locations of various data types. Go, however, does not have a direct equivalent to void pointers. This poses a challenge when designing data structures that require the ability to store arbitrary types.
According to the Go Programming Language Specification, every type in Go is a member of the empty interface "interface{}". This interface does not have any methods, making it applicable to all types. Therefore, by using the empty interface, one can effectively achieve the functionality of a void pointer in Go.
Consider the following example of a data structure that can hold any type using the empty interface:
type ArrayList struct { data []interface{} }
To add a value of any type to the ArrayList:
list := ArrayList{} list.data = append(list.data, 5) list.data = append(list.data, "Hello")
To access a value of any type from the ArrayList:
value := list.data[1] switch t := value.(type) { case int: fmt.Printf("The value is an integer: %d\n", t) case string: fmt.Printf("The value is a string: %s\n", t) case float64: fmt.Printf("The value is a float64: %f\n", t) }
In Go 1.18 and later, you can also use the built-in alias any, which is equivalent to interface{}, for even more concise code:
type ArrayList struct { data []any }
By leveraging the empty interface interface{} (or any in Go 1.18 ), Go provides a flexible mechanism to create data structures that can hold and manipulate values of arbitrary types. This effectively emulates the functionality of a void pointer in C, allowing for greater flexibility and type safety in Go programs.
The above is the detailed content of How Can I Achieve the Functionality of a C Void Pointer in Go?. For more information, please follow other related articles on the PHP Chinese website!