0
0
Goprogramming~30 mins

Implementing interfaces in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Implementing interfaces
📖 Scenario: You are building a simple program to manage different types of notifications in a system. Each notification type should be able to send a message in its own way.
🎯 Goal: Create a Go program that defines an interface for sending notifications and implements this interface with two different notification types: Email and SMS. Then, use these implementations to send messages.
📋 What You'll Learn
Define an interface called Notifier with a method Send(message string)
Create a struct called Email with a field address string
Create a struct called SMS with a field number string
Implement the Send method for both Email and SMS to print a message showing where the notification is sent
Create variables of type Email and SMS with example data
Use the Notifier interface to call Send on both notification types
Print the output messages
💡 Why This Matters
🌍 Real World
Interfaces are used in real-world Go programs to write code that works with different types in a uniform way, such as sending notifications through email, SMS, or other channels without changing the main logic.
💼 Career
Understanding interfaces is essential for Go developers because many Go libraries and frameworks use interfaces to allow flexible and testable code.
Progress0 / 4 steps
1
Create the Email and SMS structs
Create a struct called Email with a field address string and a struct called SMS with a field number string.
Go
Hint

Use the type keyword to define structs with the specified fields.

2
Define the Notifier interface
Define an interface called Notifier with a method Send(message string).
Go
Hint

Interfaces in Go are defined using the type keyword followed by the interface name and the interface keyword.

3
Implement the Send method for Email and SMS
Implement the Send(message string) method for the Email struct that prints "Sending email to {address}: {message}" and for the SMS struct that prints "Sending SMS to {number}: {message}".
Go
Hint

Use receiver functions to implement the Send method for each struct. Use fmt.Printf to print the messages.

4
Create instances and send messages using the interface
Create a variable emailNotifier of type Email with address "user@example.com" and a variable smsNotifier of type SMS with number "123-456-7890". Then create a slice of Notifier called notifiers containing both variables. Use a for loop with variable notifier to call Send("Hello World") on each notifier. This should print the messages.
Go
Hint

Create instances of Email and SMS, put them in a slice of Notifier, and loop over them to call Send.