People love single-method interfaces (SMIs) in Go. They’re simple to implement and easy to reason about. The standard library is packed with SMIs like io.Reader, io.Writer, io.Closer, io.Seeker, and more.
One cool thing about SMIs is that you don’t always need to create a full-blown struct with a method to satisfy the interface. You can define a function type, attach the interface method to it, and use it right away. This approach works well when there’s no state to maintain, so the extra struct becomes unnecessary. However, I find the syntax for this a bit abstruce. So, I’m jotting down a few examples here to reference later.
This is how interfaces are typically implemented. Here, we’ll satisfy the io.Writer interface to create a writer that logs some stats before saving data to an in-memory buffer.
We can implement io.Writer by defining a struct type, LoggingWriter, and attaching a Write method with the required signature: