Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go equivalent of a void pointer in C

Tags:

pointers

go

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?

like image 815
evanmcdonnal Avatar asked Jan 25 '12 01:01

evanmcdonnal


People also ask

What is a void pointer in C?

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.

Can you declare a void pointer in C?

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.

What does void * mean in C?

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.

Can we assign null on void pointer?

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.


1 Answers

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.

like image 145
ruakh Avatar answered Oct 19 '22 10:10

ruakh