Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Go's interface{} the same as void* in C?

Tags:

c

types

go

Since a variable of type interface{} can have any value, does that mean it is essentially a general pointer like a void* in C?

like image 314
Brenden Avatar asked Nov 19 '13 08:11

Brenden


2 Answers

While C's void * pointers and Go's interface{} variables share the property that you can store arbitrary types, there is one big difference: Go interface variables also store the type of the value they hold.

So while a C programmer is expected to make sure that any casts from void * pointers to specific types are safe, the Go runtime can check that any type assertions are correct.

The type information found in interface variables also allows for sophisticated runtime introspection through the reflect package, which would be impossible with a plain void * pointer.

like image 200
James Henstridge Avatar answered Nov 15 '22 12:11

James Henstridge


I am inclined to say "Not at all!". But I admit that it may server the same purpose of "holding whatever comes along".

  1. An interface {} is not a pointer so you cannot dereference it.
  2. You can cast a void* to anything but type asserting an interface {} might result in a runtime panic.
  3. It is complicated (or impossible) to determine the actual type a void* points to but package reflect lets you do this for interface {}.

So no! interface {} is the empty interface and has nothing to do with a void* in C with the small exception that both might be used to handle anything where you do not care about the real nature of it.

like image 6
Volker Avatar answered Nov 15 '22 14:11

Volker