0
0
Goprogramming~30 mins

Interface satisfaction in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Interface satisfaction
📖 Scenario: You are building a simple program to check if different types satisfy a common interface. This is useful when you want to ensure that different objects can be used interchangeably based on shared behavior.
🎯 Goal: Create a Go program that defines an interface and two structs. Then check if these structs satisfy the interface by assigning them to interface variables.
📋 What You'll Learn
Define an interface called Speaker with a method Speak() string
Create a struct called Dog with a method Speak() string that returns "Woof!"
Create a struct called Cat with a method Speak() string that returns "Meow!"
Assign instances of Dog and Cat to variables of type Speaker
Print the result of calling Speak() on both interface variables
💡 Why This Matters
🌍 Real World
Interfaces let you write flexible programs where different types can be used interchangeably if they share behavior. For example, different animals can be treated as speakers without knowing their exact type.
💼 Career
Understanding interface satisfaction is key for Go developers to design clean, modular, and testable code. It is widely used in real-world Go projects and libraries.
Progress0 / 4 steps
1
Define the Speaker interface and Dog struct
Write Go code to define an interface called Speaker with a method Speak() string. Then define a struct called Dog.
Go
Hint

Interfaces in Go are defined with the type keyword followed by the interface name and the interface keyword. Methods inside interfaces have no body.

2
Add the Speak() method to Dog and define Cat struct
Add a method Speak() string to the Dog struct that returns "Woof!". Then define a struct called Cat.
Go
Hint

Methods are defined with func (receiver Type) MethodName() ReturnType. The receiver d Dog means the method belongs to Dog.

3
Add the Speak() method to Cat
Add a method Speak() string to the Cat struct that returns "Meow!".
Go
Hint

Use the same method pattern as for Dog, but change the receiver to c Cat and the return string to "Meow!".

4
Assign Dog and Cat to Speaker and print results
In the main function, create variables dogSpeaker and catSpeaker of type Speaker. Assign instances of Dog and Cat to them respectively. Then print the result of calling Speak() on both variables.
Go
Hint

Use var variableName Speaker = Type{} to assign structs to interface variables. Use println() to print the results.