Laurent Knauss Software Engineer
Illustration of Go interfaces

Go Interfaces

As I was learning Go, I discovered there are three types of interfaces:

  • Built-in interfaces: Provided by the Go standard library, such as io.Reader, io.Writer, and error.
  • External interfaces: Defined in third-party packages and libraries.
  • Custom interfaces: Defined by you, the developer, to abstract behaviors in your application.

Interfaces express abstractions by defining a set of methods without concrete implementations. They enable polymorphism and decouple code from specific types.

Example: Defining the error Interface

// Built-in error interface
type error interface {
  Error() string
}

Example: Custom Error Type

package main

import (
  "fmt"
)

type MyError struct {
  Msg  string
  Code int
}

func (e MyError) Error() string {
  return fmt.Sprintf("Code: %d, Msg: %s", e.Code, e.Msg)
}

func main() {
  err := MyError{"something went wrong", 404}
  fmt.Println(err.Error()) // Code: 404, Msg: something went wrong
}