I've been playing around with Go a little bit making some data structure libraries and I have one big problem. I want the data structure to be able to contain any type, but I don't see any way to do this in Go because you can't declare void pointers and they don't have a class like NSObject that everything inherits from. How would I achieve this same functionality in Go?
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
A void pointer is nothing but a pointer variable declared using the reserved word in C 'void'. When a pointer variable is declared using keyword void – it becomes a general purpose pointer variable. Address of any variable of any data type (char, int, float etc.) can be assigned to a void pointer variable.
void* is a "pointer to anything". void ** is another level of indirection - "pointer to pointer to anything". Basically, you pass that in when you want to allow the function to return a pointer of any type.
A void pointer can be a null pointer. Thus, a void pointer refers to the type of the pointer, whereas a null pointer refers to the value (address) of the pointer.
According to the Go Programming Language Specification:
A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:
interface{}
If you search within that document for interface{}
, you'll see quite a few examples of how you can use it to do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With