When To Use An Empty Interface In Golang

Pavle Djuric
3 min readJan 15, 2023

Statically typed languages are highly beneficial.

  • They improve code readability, making it easier for developers to understand code that was written by other developers
  • They provide type checking at compile time, meaning potential runtime errors will most certainly be avoided
  • They allow for better IDE support, which improves developer productivity

However, sometimes static types narrow the flexibility of our code. This why it is useful to have a catch-all type. In Java, it is the Object class, from which all other objects inherit, in Typescript it is the Any type, and in Golang it is the empty interface. Since it does not have any methods, every possible type in Go satisfies it’s contract, by merely existing.

There are three relatively common situations where using an empty interface is perfectly appropriate, and even necessary.

  • One of the main use cases for empty interfaces is in functions or methods that need to accept a variety of types as arguments. For example, the fmt.Println() function in the Go standard library takes in a variadic empty interface as its argument, allowing it to print any type of value:
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always…

--

--

Pavle Djuric
Pavle Djuric

Written by Pavle Djuric

Software developer. 3 x AWS certified. Writing mostly about Python, Golang, backend development and Cloud computing.

Responses (1)