What if you could write code once and use it for many different things without rewriting?
Why Interface use cases in Go? - Purpose & Use Cases
Imagine you have different types of devices like a printer, scanner, and fax machine. You want to send commands to each device manually by writing separate code for each one.
Writing separate code for each device is slow and error-prone. If you add a new device, you must rewrite or duplicate code everywhere. It becomes hard to manage and easy to make mistakes.
Interfaces let you define a common set of actions that all devices must follow. You write code once to work with the interface, and any device that implements it can be used without changing your code.
func printDocument(p Printer) {
p.Print()
}
// Need separate functions for Scanner, Fax, etc.type Device interface {
Execute()
}
func useDevice(d Device) {
d.Execute()
}
// Any device implementing Execute() works hereInterfaces enable flexible and reusable code that works with many types without rewriting logic.
A payment system where different payment methods like credit card, PayPal, and bank transfer all implement a common interface to process payments seamlessly.
Manual code for each type is slow and hard to maintain.
Interfaces define shared behavior for many types.
Code using interfaces is simpler, flexible, and reusable.
Practice
interface in Go?Solution
Step 1: Understand what an interface represents
An interface in Go lists method signatures without implementations.Step 2: Identify the role of interfaces
Any type that implements those methods satisfies the interface, enabling flexible code.Final Answer:
To define a set of method signatures that a type must implement -> Option AQuick Check:
Interface = method signatures [OK]
- Confusing interfaces with structs
- Thinking interfaces hold data
- Assuming interfaces perform calculations
Speaker with a method Speak() in Go?Solution
Step 1: Recall Go interface syntax
Interfaces are declared withtype Name interface { methods }.Step 2: Match the correct syntax
type Speaker interface { Speak() } correctly declaresSpeakeras an interface with methodSpeak().Final Answer:
type Speaker interface { Speak() } -> Option DQuick Check:
Interface declaration = type Speaker interface { Speak() } [OK]
- Using 'interface' keyword alone without 'type'
- Declaring interfaces as structs
- Adding 'func' keyword inside interface methods
package main
import "fmt"
type Speaker interface {
Speak()
}
type Dog struct {}
func (d Dog) Speak() {
fmt.Println("Woof!")
}
func saySomething(s Speaker) {
s.Speak()
}
func main() {
d := Dog{}
saySomething(d)
}Solution
Step 1: Check if Dog implements Speaker
Dog has methodSpeak(), so it satisfies Speaker interface.Step 2: Trace function call
Inmain,saySomething(d)callsd.Speak(), printing "Woof!".Final Answer:
Woof! -> Option AQuick Check:
Interface method call prints "Woof!" [OK]
- Assuming interface needs explicit implementation declaration
- Expecting compilation error due to interface
- Missing method receiver syntax
package main
import "fmt"
type Reader interface {
Read()
}
type File struct {}
func (f *File) Read() {
fmt.Println("Reading file")
}
func main() {
var r Reader
f := File{}
r = f
r.Read()
}Solution
Step 1: Check method receiver type
Read() is defined on pointer receiver*File, not onFilevalue.Step 2: Understand interface assignment rules
Assigningf(value) to interfacerfails becauseFiledoes not implementRead(), only*Filedoes.Final Answer:
Cannot assign value of type File to Reader interface -> Option CQuick Check:
Pointer receiver methods require pointer type assignment [OK]
- Ignoring pointer vs value receiver difference
- Expecting interface to accept any type
- Thinking methods must return values
type Walker interface {
Walk()
}
type Runner interface {
Run()
}
type Athlete interface {
Walker
Runner
}
type Person struct {}
func (p Person) Walk() {
fmt.Println("Walking")
}
func (p Person) Run() {
fmt.Println("Running")
}Which of the following statements is true?
Solution
Step 1: Understand interface embedding
Athlete embeds Walker and Runner, so it requires both Walk() and Run() methods.Step 2: Check Person methods
Person has both Walk() and Run() methods, so it satisfies Athlete interface automatically.Final Answer:
Person implements Athlete because it has both Walk and Run methods -> Option BQuick Check:
Interface embedding means combined methods [OK]
- Thinking explicit declaration is needed
- Believing interface embedding is invalid
- Assuming partial method implementation suffices
Ready to prove it?
Pass the test and this pattern moves unknown
