Sobes.tech
Senior

Why are interfaces needed at all? Why not just use structures?

sobes.tech AI

Answer from AI

Interfaces in Go are used to define the behavior of objects without tying them to a specific implementation. They allow for writing more flexible and extensible code, support polymorphism, and facilitate testing.

If only structures are used, the code becomes tightly coupled to specific types, which makes it difficult to replace implementations or write mocks for tests.

For example, the Reader interface defines a Read method, and different types (files, buffers, network connections) can implement this interface, allowing them to be used interchangeably:

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

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

Thus, interfaces provide abstraction and loose coupling of code.