What if you could write one piece of code that works with many different things without changing a single line?
Why Interface definition 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, but each one works differently. Without a common way to talk to them, you have to write separate code for each device every time.
Writing separate code for each device is slow and confusing. If you add a new device, you must rewrite or duplicate code. This leads to mistakes and makes your program hard to maintain.
Interfaces let you define a common set of actions that different devices must follow. You write code once using the interface, and any device that implements it can be used interchangeably. This makes your code cleaner and easier to extend.
func printDocument(p Printer) {
p.Print()
}
// Need separate functions for Scanner, Fax, etc.type Device interface {
Execute()
}
func operate(d Device) {
d.Execute()
}
// Any device implementing Execute() can be used hereInterfaces enable writing flexible code that works with many types without changing the core logic.
Think of a music player app that can play songs from different sources: local files, streaming services, or radio. An interface lets the app treat all sources the same way, so you can add new sources easily.
Interfaces define a common set of behaviors for different types.
They reduce code duplication and errors.
They make programs easier to extend and maintain.
Practice
Solution
Step 1: Understand what an interface is
An interface in Go specifies method signatures but does not provide their implementation.Step 2: Differentiate from other types
Concrete types have fields and method implementations, unlike interfaces.Final Answer:
A set of method signatures without implementation -> Option CQuick Check:
Interface = method signatures only [OK]
- Thinking interfaces hold data
- Confusing interfaces with structs
- Assuming interfaces implement methods
Shape with a method Area() returning a float64?Solution
Step 1: Recall Go interface syntax
Interfaces are defined with the keywordtype, name, theninterfaceand method signatures inside braces.Step 2: Check each option
type Shape interface { Area() float64 } matches correct syntax. Options B, C, and D misuse keywords or structure.Final Answer:
type Shape interface { Area() float64 } -> Option DQuick Check:
Correct interface syntax = type Shape interface { Area() float64 } [OK]
- Using 'interface' keyword alone without 'type'
- Defining methods inside struct instead of interface
- Placing 'func' keyword inside interface method
package main
import "fmt"
type Printer interface {
Print()
}
type Document struct {
content string
}
func (d Document) Print() {
fmt.Println(d.content)
}
func main() {
var p Printer
d := Document{"Hello, Go!"}
p = d
p.Print()
}Solution
Step 1: Check interface implementation
Document has a method Print() matching Printer interface, so Document implements Printer.Step 2: Assign and call method
Variable p of type Printer is assigned d (Document), then p.Print() calls Document.Print(), printing content.Final Answer:
Hello, Go! -> Option BQuick Check:
Interface method calls concrete method [OK]
- Thinking interface needs explicit implementation declaration
- Expecting compile error on assignment
- Assuming interface variable is nil
type Reader interface {
Read(p []byte) (n int, err error)
}
type File struct {}
func (f File) Read() (int, error) {
return 0, nil
}Solution
Step 1: Compare method signatures
Reader interface expects Read with parameter []byte and two return values.Step 2: Check File's Read method
File's Read method has no parameters, so signature does not match interface.Final Answer:
Method Read has wrong signature, missing parameter -> Option AQuick Check:
Method signature must match interface [OK]
- Ignoring method parameters in implementation
- Assuming method name alone is enough
- Thinking interface methods can't have parameters
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
type MyFile struct {}
func (f MyFile) Read(p []byte) (int, error) {
return len(p), nil
}
func (f MyFile) Write(p []byte) (int, error) {
return len(p), nil
}Which statement is true about
MyFile and ReadWriter?Solution
Step 1: Understand interface embedding
ReadWriter embeds Reader and Writer, so it requires both methods.Step 2: Check MyFile methods
MyFile has both Read and Write methods matching signatures.Step 3: Confirm implementation
Since MyFile has all required methods, it implements ReadWriter.Final Answer:
MyFile implements ReadWriter because it has both Read and Write methods -> Option AQuick Check:
Embedded interfaces require all methods [OK]
- Thinking embedding interfaces is invalid
- Assuming partial method implementation suffices
- Confusing interface embedding with inheritance
Ready to prove it?
Pass the test and this pattern moves unknown
