Sobes.tech
Middle+

Why use interfaces in Go?

sobes.tech AI

Answer from AI

Interfaces in Go are used to define a set of methods that a type must implement, without specifying the concrete implementation. This allows for creating flexible and extensible architectures.

Why use interfaces:

  • Abstraction: enables working with different types through a common interface, independent of specific implementations.
  • Polymorphism: allows writing functions and methods that accept interfaces and use any types that implement these interfaces.
  • Testability: makes it easy to create mocks and stubs for testing by implementing interfaces.
  • Loose coupling: code becomes less coupled, making it easier to change implementations without modifying the calling code.

Example:

// Interface for a logger
 type Logger interface {
     Log(message string)
 }

// Implementation of the interface
 type ConsoleLogger struct {}

 func (c ConsoleLogger) Log(message string) {
     fmt.Println(message)
 }

func Process(l Logger) {
    l.Log("Start processing")
    // ...
    l.Log("End processing")
}

func main() {
    var logger Logger = ConsoleLogger{}
    Process(logger)
}

Thus, interfaces in Go allow writing more modular, extensible, and testable code.