Interface definition in Go - Time & Space Complexity
When we define an interface in Go, we want to understand how the program's work grows as we use it more.
We ask: How much time does it take to check if a type matches an interface?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
func saySomething(s Speaker) {
fmt.Println(s.Speak())
}
func main() {
d := Dog{}
saySomething(d)
}
This code defines an interface and a type that implements it, then calls a function using the interface.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the method Speak() through the interface.
- How many times: Once in this example, but could be many times if called repeatedly.
Each call to a method via an interface involves a small fixed cost to find the right method.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 method call |
| 10 | 10 method calls |
| 100 | 100 method calls |
Pattern observation: The time grows directly with the number of calls, each call costs about the same.
Time Complexity: O(n)
This means the total time grows in a straight line with how many times you call the interface method.
[X] Wrong: "Calling a method through an interface is slower and grows exponentially with calls."
[OK] Correct: Each call has a small fixed cost, so time grows linearly, not exponentially.
Understanding how interface calls scale helps you write clear and efficient Go code, a useful skill in many projects.
"What if we called multiple methods on the interface instead of just one? How would the time complexity change?"