Bird
Raised Fist0
Goprogramming~10 mins

Interface use cases in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Interface use cases
Define Interface
↓
Create Structs implementing Interface
↓
Assign Structs to Interface Variable
↓
Call Interface Methods
↓
Use Polymorphism: Different Structs, Same Interface
↓
Pass Interface to Functions
↓
Interface Enables Flexible Code
This flow shows how interfaces are defined, implemented by structs, assigned, and used to enable flexible and polymorphic code.
Execution Sample
Go
package main
import "fmt"
type Speaker interface {
    Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
    return "Woof!"
}
func main() {
    var s Speaker
    d := Dog{}
    s = d
    fmt.Println(s.Speak())
}
Defines an interface Speaker and a struct Dog implementing Speak method.
Execution Table
StepActionEvaluationResult
1Define interface Speaker with Speak() stringInterface createdSpeaker interface ready
2Define struct DogStruct createdDog struct ready
3Implement Speak() method for DogMethod attachedDog implements Speaker
4Create Dog instance dd := Dog{}d is Dog{}
5Assign d to variable s of type Speakervar s Speaker = ds holds Dog as Speaker
6Call s.Speak()s.Speak()"Woof!" returned
7Pass s to function that accepts Speakerfunc greet(sp Speaker) { fmt.Println(sp.Speak()) }Function prints "Woof!"
8Create another struct Cat implementing SpeakerCat struct with Speak() returns "Meow!"Cat implements Speaker
9Assign Cat instance to s and call Speak()s = Cat{}s.Speak() returns "Meow!"
10ExitNo more stepsProgram ends
💡 All interface use cases demonstrated, program ends
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 9Final
dundefinedDog{}Dog{}Dog{}Dog{}
snilnilDog as SpeakerCat as SpeakerCat as Speaker
Key Moments - 3 Insights
Why can variable s hold different struct types?
Because s is of interface type Speaker, it can hold any value whose type implements the Speaker interface, as shown in execution_table rows 5 and 9.
What happens when we call s.Speak()?
The method of the actual struct stored in s is called, demonstrating polymorphism (rows 6 and 9).
Why define functions accepting interface types?
Functions accepting interfaces can work with any struct implementing that interface, making code flexible and reusable (row 7).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of s after step 5?
ACat struct stored as Speaker interface
Bnil
CDog struct stored as Speaker interface
DUndefined
💡 Hint
Check the 'Result' column in row 5 of execution_table
At which step does s hold a Cat struct?
AStep 6
BStep 9
CStep 7
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table row 9
If Dog did not implement Speak(), what would happen when assigning d to s at step 5?
ACompilation error
Bs would hold nil
Cs would hold d anyway
DRuntime panic
💡 Hint
Interfaces require implementing methods; see step 3 and 5 in execution_table
Concept Snapshot
Interface use cases in Go:
- Define interface with method signatures
- Structs implement interface by defining methods
- Interface variables can hold any implementing struct
- Enables polymorphism: same interface, different behaviors
- Pass interfaces to functions for flexible code
Full Transcript
This visual execution traces how interfaces work in Go. First, an interface Speaker is defined with a Speak method. Then, a struct Dog implements this method. A Dog instance is assigned to a variable s of type Speaker. Calling s.Speak() runs Dog's method, returning "Woof!". Later, another struct Cat also implements Speaker. Assigning Cat to s and calling Speak returns "Meow!". This shows how interfaces enable polymorphism and flexible code by allowing different structs to be used interchangeably through a common interface.

Practice

(1/5)
1. What is the main purpose of an interface in Go?
easy
A. To define a set of method signatures that a type must implement
B. To store data values of different types
C. To create a new data type with fields
D. To perform arithmetic operations

Solution

  1. Step 1: Understand what an interface represents

    An interface in Go lists method signatures without implementations.
  2. Step 2: Identify the role of interfaces

    Any type that implements those methods satisfies the interface, enabling flexible code.
  3. Final Answer:

    To define a set of method signatures that a type must implement -> Option A
  4. Quick Check:

    Interface = method signatures [OK]
Hint: Interfaces list methods, not data or operations [OK]
Common Mistakes:
  • Confusing interfaces with structs
  • Thinking interfaces hold data
  • Assuming interfaces perform calculations
2. Which of the following is the correct way to declare an interface named Speaker with a method Speak() in Go?
easy
A. func Speaker() interface { Speak() }
B. interface Speaker { func Speak() }
C. type Speaker struct { Speak() }
D. type Speaker interface { Speak() }

Solution

  1. Step 1: Recall Go interface syntax

    Interfaces are declared with type Name interface { methods }.
  2. Step 2: Match the correct syntax

    type Speaker interface { Speak() } correctly declares Speaker as an interface with method Speak().
  3. Final Answer:

    type Speaker interface { Speak() } -> Option D
  4. Quick Check:

    Interface declaration = type Speaker interface { Speak() } [OK]
Hint: Use 'type Name interface { ... }' to declare interfaces [OK]
Common Mistakes:
  • Using 'interface' keyword alone without 'type'
  • Declaring interfaces as structs
  • Adding 'func' keyword inside interface methods
3. What will be the output of the following Go code?
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)
}
medium
A. Woof!
B. Compilation error
C. Runtime panic
D. No output

Solution

  1. Step 1: Check if Dog implements Speaker

    Dog has method Speak(), so it satisfies Speaker interface.
  2. Step 2: Trace function call

    In main, saySomething(d) calls d.Speak(), printing "Woof!".
  3. Final Answer:

    Woof! -> Option A
  4. Quick Check:

    Interface method call prints "Woof!" [OK]
Hint: Check if type has all interface methods to predict output [OK]
Common Mistakes:
  • Assuming interface needs explicit implementation declaration
  • Expecting compilation error due to interface
  • Missing method receiver syntax
4. Identify the error in this Go code snippet using interfaces:
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()
}
medium
A. Interface Reader cannot have methods
B. Method Read() must return a value
C. Cannot assign value of type File to Reader interface
D. No error, code runs fine

Solution

  1. Step 1: Check method receiver type

    Read() is defined on pointer receiver *File, not on File value.
  2. Step 2: Understand interface assignment rules

    Assigning f (value) to interface r fails because File does not implement Read(), only *File does.
  3. Final Answer:

    Cannot assign value of type File to Reader interface -> Option C
  4. Quick Check:

    Pointer receiver methods require pointer type assignment [OK]
Hint: Pointer receiver methods need pointer type to satisfy interfaces [OK]
Common Mistakes:
  • Ignoring pointer vs value receiver difference
  • Expecting interface to accept any type
  • Thinking methods must return values
5. Given these types and interfaces:
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?
hard
A. Person must explicitly declare it implements Athlete
B. Person implements Athlete because it has both Walk and Run methods
C. Athlete interface cannot embed other interfaces
D. Person only implements Walker, not Athlete

Solution

  1. Step 1: Understand interface embedding

    Athlete embeds Walker and Runner, so it requires both Walk() and Run() methods.
  2. Step 2: Check Person methods

    Person has both Walk() and Run() methods, so it satisfies Athlete interface automatically.
  3. Final Answer:

    Person implements Athlete because it has both Walk and Run methods -> Option B
  4. Quick Check:

    Interface embedding means combined methods [OK]
Hint: Embedded interfaces combine methods; implement all to satisfy [OK]
Common Mistakes:
  • Thinking explicit declaration is needed
  • Believing interface embedding is invalid
  • Assuming partial method implementation suffices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard