Go Data Structures: Interfaces

Created on 2023-02-08T19:17:54-06:00

Return to the Index

This card pertains to a resource available on the internet.

This card can also be read via Gemini.

To pass an object to an interface you construct a "fat pointer," which is a pointer to the value and a pointer to the method table.

This is roughly equivalent to something like:

struct Butt {
  // ...
};
struct MethodTable {
  void (*touch_butt)(Butt* self);
};
struct FatPointer {
  Butt* self;
  MethodTable table;
};
void some_interface(FatPointer* obj);

A common C-ism is to make structures of function pointers and pass those around as interfaces. Go just automates this somewhat by having the compiler see if you have the methods and generates the boilerplates for you.

How it works

An object stores one or more slots for values.

An interface defines a set of functions which may be run against an object.

A method table is a set of pointers to functions which implement the functions required by an interface.

An object can fulfill an interface if a method table can be constructed for it.