0
0
Goprogramming~30 mins

Why interfaces are used in Go - See It in Action

Choose your learning style9 modes available
Why interfaces are used
📖 Scenario: Imagine you are building a program that handles different types of notifications, like emails and SMS messages. Each notification type sends messages differently, but your program should treat them the same way when sending.
🎯 Goal: Learn how to use interfaces in Go to write flexible code that can work with different notification types without changing the main sending logic.
📋 What You'll Learn
Create a struct for Email notification
Create a struct for SMS notification
Define an interface called Notifier with a method Send
Implement the Send method for both Email and SMS structs
Write a function that accepts the Notifier interface and calls Send
Demonstrate sending notifications using the interface
💡 Why This Matters
🌍 Real World
Interfaces are used in real programs to handle different data types with common behavior, like payment methods, shapes in graphics, or notification systems.
💼 Career
Understanding interfaces is key for Go developers to write clean, reusable, and scalable code in professional software projects.
Progress0 / 4 steps
1
DATA SETUP: Create Email and SMS structs
Create two structs called Email and SMS. The Email struct should have a field Address of type string. The SMS struct should have a field PhoneNumber of type string.
Go
Hint

Use type Email struct { Address string } and similarly for SMS.

2
CONFIGURATION: Define Notifier interface
Define an interface called Notifier with a method Send() that returns nothing.
Go
Hint

Use type Notifier interface { Send() } to define the interface.

3
CORE LOGIC: Implement Send method for Email and SMS
Implement the Send() method for both Email and SMS structs. For Email, print "Sending email to " followed by the Address. For SMS, print "Sending SMS to " followed by the PhoneNumber.
Go
Hint

Define methods with func (e Email) Send() and func (s SMS) Send() that print the messages.

4
OUTPUT: Use Notifier interface to send notifications
Create a function called Notify that takes a parameter n of type Notifier and calls n.Send(). Then create an Email with Address "alice@example.com" and an SMS with PhoneNumber "+1234567890". Call Notify with both values. Print the output.
Go
Hint

Define Notify function and call it with Email and SMS instances inside main().