Bird
Raised Fist0
Goprogramming~10 mins

Interface satisfaction in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Interface satisfaction
Define Interface
↓
Define Struct
↓
Check if Struct has all Interface Methods
Yes↓
Struct satisfies Interface
↓
Use Struct as Interface Type
The program defines an interface and a struct, then checks if the struct implements all interface methods to satisfy the interface, allowing it to be used as that interface type.
Execution Sample
Go
package main
import "fmt"
type Speaker interface {
    Speak() string
}
type Person struct {
    name string
}
func (p Person) Speak() string {
    return "Hello, " + p.name
}
func main() {
    var s Speaker
    p := Person{name: "Alice"}
    s = p
    fmt.Println(s.Speak())
}
This code shows a struct Person implementing the Speaker interface by defining Speak(), then using a Person as a Speaker.
Execution Table
StepActionEvaluationResult
1Define interface Speaker with method Speak()Interface Speaker createdSpeaker requires Speak() string
2Define struct Person with field nameStruct Person createdPerson{name string}
3Define method Speak() on PersonPerson now has Speak() methodPerson satisfies Speaker interface
4In main, declare variable s of type Speakers is nil interface variables = nil
5Create Person p with name "Alice"p = Person{name:"Alice"}p holds data
6Assign p to s (interface variable)Check if Person satisfies SpeakerYes, assignment allowed
7Call s.Speak()Calls Person.Speak()Returns "Hello, Alice"
8Print resultOutput to consoleHello, Alice
💡 Program ends after printing the greeting string.
Variable Tracker
VariableStartAfter Step 5After Step 6After Step 7Final
snilnilPerson{name:"Alice"}Person{name:"Alice"}Person{name:"Alice"}
pundefinedPerson{name:"Alice"}Person{name:"Alice"}Person{name:"Alice"}Person{name:"Alice"}
Key Moments - 3 Insights
Why can we assign a Person to a Speaker variable without explicit declaration?
Because Person has a method Speak() matching the Speaker interface, Go automatically knows Person satisfies Speaker (see execution_table step 6).
What happens if Person does not implement Speak()?
The assignment s = p would fail to compile because Person wouldn't satisfy Speaker (refer to execution_table step 6 where the check happens).
Does the interface variable s hold the actual Person data or just a reference?
The interface variable s holds a copy of the Person value and the method set, so calling s.Speak() uses Person's method (see variable_tracker after step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, why is the assignment s = p allowed?
ABecause Person has a Speak() method matching Speaker interface
BBecause s is declared as Person type
CBecause p is an interface variable
DBecause Speak() returns an int
💡 Hint
Check execution_table step 6 where the interface satisfaction is confirmed.
According to variable_tracker, what is the value of s after step 7?
Anil
BPerson{name:"Alice"}
CSpeaker interface with no value
DEmpty string
💡 Hint
Look at variable_tracker column 'After Step 7' for variable s.
If Person did not implement Speak(), what would happen at step 6?
AAssignment would succeed anyway
BProgram would panic at runtime
CCompilation error due to interface not satisfied
DSpeak() would be called on nil
💡 Hint
Refer to key_moments about interface satisfaction and execution_table step 6.
Concept Snapshot
Interface satisfaction in Go:
- Define interface with method signatures
- Define struct with matching methods
- Struct automatically satisfies interface if all methods match
- Assign struct value to interface variable
- Call interface methods which invoke struct's implementations
Full Transcript
This example shows how a Go struct satisfies an interface by implementing all required methods. The interface Speaker requires a Speak() method returning a string. The struct Person defines Speak() returning a greeting with its name. In main, a variable s of type Speaker is declared. A Person value p is created with name "Alice". Assigning p to s works because Person satisfies Speaker. Calling s.Speak() calls Person's Speak() method and prints "Hello, Alice". The variable tracker shows s holds the Person value after assignment. If Person lacked Speak(), the assignment would fail to compile. This demonstrates Go's implicit interface satisfaction by method matching.

Practice

(1/5)
1. Which statement best describes how a type satisfies an interface in Go?
easy
A. A type satisfies an interface by implementing all the methods declared in the interface.
B. A type satisfies an interface only if it explicitly declares it implements the interface.
C. A type satisfies an interface by embedding the interface in its struct definition.
D. A type satisfies an interface by having the same name as the interface.

Solution

  1. Step 1: Understand interface satisfaction in Go

    In Go, a type satisfies an interface if it implements all the methods declared in that interface.
  2. Step 2: Check explicit declaration requirement

    Go does not require explicit declaration; satisfaction is implicit by method implementation.
  3. Final Answer:

    A type satisfies an interface by implementing all the methods declared in the interface. -> Option A
  4. Quick Check:

    Interface satisfaction = implicit method implementation [OK]
Hint: Remember: Implement all methods, no explicit declaration needed [OK]
Common Mistakes:
  • Thinking explicit declaration is required
  • Confusing embedding with satisfaction
  • Matching names instead of methods
2. Which of the following Go code snippets correctly shows a type satisfying an interface Speaker with method Speak()?
easy
A. type Speaker interface { Speak() string } type Dog struct {} func (d Dog) speak() string { return "Woof" }
B. type Speaker interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof" }
C. type Speaker interface { Speak() string } type Dog struct {} func Speak(d Dog) string { return "Woof" }
D. type Speaker interface { Speak() string } type Dog struct {} func (d *Dog) Speak() int { return 1 }

Solution

  1. Step 1: Check method signature and receiver

    type Speaker interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof" } defines Speak() with correct receiver (d Dog) and return type string.
  2. Step 2: Verify method name and return type match interface

    type Speaker interface { Speak() string } type Dog struct {} func (d Dog) speak() string { return "Woof" } has lowercase speak(), so it does not satisfy interface. type Speaker interface { Speak() string } type Dog struct {} func Speak(d Dog) string { return "Woof" } defines a function, not a method. type Speaker interface { Speak() string } type Dog struct {} func (d *Dog) Speak() int { return 1 } has wrong return type int.
  3. Final Answer:

    type Speaker interface { Speak() string } type Dog struct {} func (d Dog) Speak() string { return "Woof" } -> Option B
  4. Quick Check:

    Method name and signature must match exactly [OK]
Hint: Method name and signature must match interface exactly [OK]
Common Mistakes:
  • Using lowercase method names
  • Defining functions instead of methods
  • Mismatching return types
3. What will be the output of the following Go program?
package main
import "fmt"

type Reader interface {
  Read() string
}

type File struct {}
func (f File) Read() string {
  return "file content"
}

func printContent(r Reader) {
  fmt.Println(r.Read())
}

func main() {
  f := File{}
  printContent(f)
}
medium
A. No output
B. Compilation error: File does not satisfy Reader
C. file content
D. Runtime panic

Solution

  1. Step 1: Check if File satisfies Reader interface

    File has method Read() string, so it satisfies Reader.
  2. Step 2: Trace function call and output

    In main, f is passed to printContent, which calls Read() and prints "file content".
  3. Final Answer:

    file content -> Option C
  4. Quick Check:

    Interface satisfied, method called, prints string [OK]
Hint: Check method presence to confirm interface satisfaction [OK]
Common Mistakes:
  • Assuming explicit declaration needed
  • Confusing method receiver types
  • Expecting runtime errors without cause
4. Identify the error in the following Go code that prevents Car from satisfying the Vehicle interface:
package main
import "fmt"

type Vehicle interface {
  Drive()
}

type Car struct {}
func (c *Car) Drive() {
  fmt.Println("Driving")
}

func main() {
  var v Vehicle
  c := Car{}
  v = c
  v.Drive()
}
medium
A. Car does not satisfy Vehicle because Drive has pointer receiver but v is assigned a value.
B. Drive method has wrong return type.
C. Vehicle interface requires Drive with parameters.
D. No error, code runs fine.

Solution

  1. Step 1: Check method receiver type

    Drive is defined with pointer receiver (*Car), so only *Car satisfies Vehicle, not Car value.
  2. Step 2: Check assignment in main

    Variable v is assigned c which is a value, not pointer, causing mismatch.
  3. Final Answer:

    Car does not satisfy Vehicle because Drive has pointer receiver but v is assigned a value. -> Option A
  4. Quick Check:

    Pointer receiver methods require pointer type for interface satisfaction [OK]
Hint: Pointer receiver methods need pointer type to satisfy interface [OK]
Common Mistakes:
  • Assigning value instead of pointer to interface
  • Ignoring receiver type in method
  • Assuming method signature mismatch
5. Given the interface and types below, which assignment will cause a compile-time error due to interface satisfaction rules?
type Writer interface {
  Write(data string) error
}

type Logger struct {}
func (l Logger) Write(data string) error {
  return nil
}

type FileWriter struct {}
func (f *FileWriter) Write(data string) error {
  return nil
}

var w Writer

// Which assignment is invalid?
// A) w = Logger{}
// B) w = &Logger{}
// C) w = FileWriter{}
// D) w = &FileWriter{}
hard
A. w = &FileWriter{}
B. w = &Logger{}
C. w = Logger{}
D. w = FileWriter{}

Solution

  1. Step 1: Analyze Logger methods

    Logger has Write with value receiver, so both Logger and *Logger satisfy Writer.
  2. Step 2: Analyze FileWriter methods

    FileWriter has Write with pointer receiver, so only *FileWriter satisfies Writer, not FileWriter value.
  3. Step 3: Check assignments

    Assignment C tries to assign FileWriter{} value to Writer, which is invalid.
  4. Final Answer:

    w = FileWriter{} causes compile-time error due to missing method on value receiver. -> Option D
  5. Quick Check:

    Pointer receiver methods require pointer type for interface [OK]
Hint: Pointer receiver methods need pointer type for interface satisfaction [OK]
Common Mistakes:
  • Assigning value type when method has pointer receiver
  • Assuming pointer and value types are interchangeable
  • Ignoring method receiver type
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