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:
-
Abstraction and Polymorphism — when you need to define a set of methods that different types must implement to work uniformly. For example, the
io.Readerinterface allows reading data from various sources (files, networks, buffers) without knowing the specific type. -
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)
}