Middle+
Where are interfaces practically useful? Provide a real example.
sobes.tech AI
Answer from AI
Interfaces in Go are useful for defining contracts that types must implement, allowing for flexible and extensible code. They are especially helpful for abstracting implementation details and simplifying testing.
A real-world example: suppose you have a service that sends notifications in different ways — via email, SMS, and push notifications. You can define a Notifier interface with a method Notify(message string) error and implement it for each notification type. This allows working with the interface in code without depending on specific implementations.
// Interface
type Notifier interface {
Notify(message string) error
}
// Implementation for Email
type EmailNotifier struct {}
func (e EmailNotifier) Notify(message string) error {
// email sending logic
return nil
}
// Implementation for SMS
type SMSNotifier struct {}
func (s SMSNotifier) Notify(message string) error {
// SMS sending logic
return nil
}
func SendNotification(n Notifier, msg string) {
err := n.Notify(msg)
if err != nil {
// error handling
}
}
// Usage
email := EmailNotifier{}
sms := SMSNotifier{}
SendNotification(email, "Hello via Email")
SendNotification(sms, "Hello via SMS")
This approach simplifies adding new notification methods without changing existing code.