Sobes.tech
Junior — Middle

Name two scenarios where using interfaces in Go would be justified and useful.

sobes.tech AI

Answer from AI

Interfaces in Go are useful in the following scenarios:

  1. Abstraction and Polymorphism — when you need to define a set of methods that different types must implement to work uniformly. For example, the io.Reader interface allows reading data from various sources (files, networks, buffers) without knowing the specific type.

  2. Testing and Mocking — interfaces make it easy to replace real implementations with stubs or mocks when writing tests, which simplifies component isolation and logic verification.

Example of an interface and its implementation:

// Interface
 type Notifier interface {
     Notify(message string) error
 }

// Implementation
 type EmailNotifier struct {}

 func (e EmailNotifier) Notify(message string) error {
     // send email
     return nil
 }

// Usage
 func SendAlert(n Notifier, msg string) {
     n.Notify(msg)
 }
Name two scenarios where using interfaces in Go would… - sobes.tech