Error interface in Go - Time & Space Complexity
When working with the error interface in Go, it's important to understand how the program's steps grow as it handles errors.
We want to see how the time to check or create errors changes as the program runs.
Analyze the time complexity of the following code snippet.
func checkErrors(errors []error) {
for _, err := range errors {
if err != nil {
println(err.Error())
}
}
}
This code goes through a list of errors and prints the message for each non-nil error.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the slice of errors.
- How many times: Once for each error in the list.
As the number of errors increases, the program checks each one in turn.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and possible prints |
| 100 | About 100 checks and possible prints |
| 1000 | About 1000 checks and possible prints |
Pattern observation: The work grows directly with the number of errors.
Time Complexity: O(n)
This means the time to check errors grows in a straight line with the number of errors.
[X] Wrong: "Checking errors is instant and does not depend on how many errors there are."
[OK] Correct: Each error must be checked one by one, so more errors mean more work.
Understanding how error handling scales helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we stored errors in a map instead of a slice? How would the time complexity change when checking for errors?"