Sobes.tech
Senior

What are interfaces in Go and what are they used for?

sobes.tech AI

Answer from AI

Interfaces in Go are a way to describe behavior through a set of methods that a type must implement to be considered as conforming to that interface.

Features and purpose:

  • An interface defines a contract: what methods a type must have.
  • A type is considered to implement an interface if it has all the methods of the interface — this is called implicit implementation, without explicit declaration.
  • They allow writing flexible and extensible code, operating on abstractions rather than concrete types.
  • Used for polymorphism: different types can be used through a single interface.

Example:

type Reader interface {
    Read(p []byte) (n int, err error)
}

func ReadData(r Reader) {
    buf := make([]byte, 100)
    n, err := r.Read(buf)
    // data processing
}

Here, the ReadData function can work with any type that implements the Read method, without worrying about the specific implementation.

Thus, interfaces enable building modular, testable, and extensible code.