Go · Level 2 Interfaces

Interfaces

Define a Notifier interface in Go and send one alert through email and Slack: any type with the right method satisfies an interface, with no implements keyword.

  • an interface lists methods
  • satisfied implicitly, no implements
  • the signature must match exactly

An interface lists methods, and any type that has them satisfies it, with no implements keyword. Trap: the method must match exactly; Send(msg string) error is not Send(msg string) string.

type Notifier interface {
    Send(msg string) string
}

type Log struct{}

func (Log) Send(msg string) string {
    return "log: " + msg
}

Write types Email{To string} and Slack{Channel string} that satisfy Notifier, and Broadcast(ns []Notifier, msg string) []string that collects every result. Email{"[email protected]"}.Send("hi") → "email [email protected]: hi", Slack{"ops"}.Send("hi") → "slack #ops: hi".

solution.go
Test Suites Pending
Output