0
0
Goprogramming~30 mins

Interface use cases in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Interface Use Cases in Go
📖 Scenario: You are building a simple system to handle different types of notifications in a company. Notifications can be sent via Email or SMS. Each notification type has its own way of sending messages, but your system should treat them the same way using an interface.
🎯 Goal: Create a Go program that uses an interface to send notifications through Email and SMS. You will define the interface, implement it with two types, and then use the interface to send messages.
📋 What You'll Learn
Create an interface called Notifier with a method Send(message string)
Create two structs called EmailNotifier and SMSNotifier
Implement the Send method for both EmailNotifier and SMSNotifier
Create a slice of Notifier containing both EmailNotifier and SMSNotifier
Use a for loop to call Send on each notifier with the message "Hello, team!"
Print the output of each Send call
💡 Why This Matters
🌍 Real World
Interfaces let you write flexible code that can work with different types of objects in a uniform way, like sending notifications through various channels.
💼 Career
Understanding interfaces is key for Go developers to build modular, testable, and maintainable software systems.
Progress0 / 4 steps
1
Define the Notifier interface and structs
Create an interface called Notifier with a method Send(message string). Then create two structs called EmailNotifier and SMSNotifier with no fields.
Go
Hint

Interfaces in Go are defined using the type keyword followed by the interface name and the methods inside curly braces.

2
Implement the Send method for both structs
Write the Send(message string) method for EmailNotifier that prints "Sending Email: " followed by the message. Also write the Send(message string) method for SMSNotifier that prints "Sending SMS: " followed by the message.
Go
Hint

Methods are defined with a receiver in parentheses before the method name. Use println to print the message.

3
Create a slice of Notifier and add instances
Create a variable called notifiers which is a slice of Notifier. Add one EmailNotifier and one SMSNotifier to this slice.
Go
Hint

Use a slice literal to create the slice with both struct instances inside curly braces.

4
Use a loop to send the message and print output
Add a main function if not present. Use a for loop with variable _, notifier to iterate over notifiers. Call notifier.Send("Hello, team!") inside the loop to send the message. This will print the output.
Go
Hint

The for loop iterates over the slice and calls the Send method on each notifier, printing the message.