Home >Backend Development >Golang >How Can I Simulate Void Pointers in Go to Store Data of Any Type?
Implementing a Void Pointer in Go
In Go, the absence of void pointers and inheritance can pose a challenge when attempting to create data structures that can hold values of any type. However, there is a solution that leverages the concept of the empty interface:
interface{}
According to the Go Programming Language Specification, every type implements the empty interface, meaning it can represent any type. By declaring a variable or structure field of type interface{}, you can effectively store values of any type in that location.
This technique provides similar functionality to C's void pointers, allowing you to handle values of arbitrary types without needing to declare specific types. For instance, consider the following example:
type DataStore struct { Data []interface{} } func (ds *DataStore) Add(value interface{}) { ds.Data = append(ds.Data, value) } func main() { ds := &DataStore{} ds.Add("Hello") ds.Add(42) ds.Add(struct{ Name string }{Name: "Alice"}) // Print the stored values for _, v := range ds.Data { fmt.Println(v) } }
In this example, the DataStore struct contains a slice of interface{} values. We can then dynamically add values of different types into this slice using the Add method. The main function demonstrates how to store and print values of various types in our DataStore.
Since Go 1.18, an alias for interface{} called any is available, providing a convenient shorthand:
type DataStore struct { Data []any }
The above is the detailed content of How Can I Simulate Void Pointers in Go to Store Data of Any Type?. For more information, please follow other related articles on the PHP Chinese website!