Interface satisfaction in Go - Time & Space Complexity
When working with interfaces in Go, it's important to understand how the program checks if a type fits an interface.
We want to see how the time needed to confirm this fit changes as the program runs.
Analyze the time complexity of the following code snippet.
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 // interface satisfaction happens here
fmt.Println(s.Speak())
}
This code checks if a Person type satisfies the Speaker interface by assigning it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The program checks the method set of the Person type against the Speaker interface methods.
- How many times: This check happens once at assignment time for this example.
Explain the growth pattern intuitively.
| Input Size (number of interface methods) | Approx. Operations |
|---|---|
| 1 | 1 method check |
| 5 | 5 method checks |
| 10 | 10 method checks |
Pattern observation: The time to check grows linearly with the number of methods in the interface.
Time Complexity: O(n)
This means the time to confirm interface satisfaction grows directly with the number of methods the interface has.
[X] Wrong: "Checking if a type satisfies an interface is instant and does not depend on the interface size."
[OK] Correct: The program must check each method in the interface against the type's methods, so more methods mean more checks.
Understanding how interface satisfaction works helps you reason about Go's type system and performance in real programs.
"What if the interface had embedded interfaces? How would that affect the time complexity of satisfaction checks?"