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?"
Practice
What does the Error() method in Go's error interface return?
Solution
Step 1: Understand the error interface
Theerrorinterface in Go defines a single methodError()that returns a string.Step 2: Identify the return type of Error()
TheError()method returns a string that describes the error message.Final Answer:
A string describing the error message -> Option CQuick Check:
Error() returns string message [OK]
- Thinking Error() returns an integer code
- Assuming Error() returns a boolean
- Confusing Error() with returning an error object pointer
Which of the following is the correct way to declare a function in Go that returns an error?
func doSomething() ???
Solution
Step 1: Recall function return types for errors
In Go, functions that can fail often return anerrortype as the last return value.Step 2: Check the syntax for returning only an error
The correct syntax for a function returning only an error isfunc doSomething() error.Final Answer:
func doSomething() error -> Option AQuick Check:
Function returns error type only [OK]
- Returning *error instead of error
- Returning string instead of error
- Returning multiple values without parentheses
What will be the output of the following Go program?
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("file not found")
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("No error")
}
}Solution
Step 1: Understand errors.New usage
Theerrors.Newfunction creates a new error with the message "file not found".Step 2: Check the if condition and output
Sinceerris not nil, the program printserr.Error(), which is the string "file not found".Final Answer:
file not found -> Option AQuick Check:
Non-nil error prints message [OK]
- Expecting 'No error' output
- Thinking err is nil after errors.New
- Confusing err.Error() with err itself
Identify the error in this Go code snippet:
func check() error {
var err error
if err != nil {
return err
}
return nil
}Solution
Step 1: Analyze variable initialization
The variableerris declared but never assigned a value, so it defaults tonil.Step 2: Evaluate the if condition
Sinceerrisnil, the conditionerr != nilis false, so the return inside if never runs.Final Answer:
Variable err is never assigned, so err != nil is always false -> Option BQuick Check:
Unassigned error variable is nil [OK]
- Assuming err is non-nil by default
- Thinking function must return string
- Confusing nil return with error
Given this Go function that returns an error, how can you modify it to wrap the original error with additional context?
func readFile() error {
return errors.New("file missing")
}Choose the best way to add context "readFile failed:" before the original error message.
Solution
Step 1: Understand error wrapping in Go
Go 1.13+ supports error wrapping usingfmt.Errorfwith the%wverb to wrap an error with context.Step 2: Check options for wrapping
return fmt.Errorf("readFile failed: %w", errors.New("file missing")) usesfmt.Errorf("readFile failed: %w", errors.New("file missing")), which correctly wraps the original error with context.Step 3: Identify incorrect options
return errors.New("readFile failed: file missing") creates a new error string but does not wrap the original error. return errors.Wrap(errors.New("file missing"), "readFile failed") useserrors.Wrapwhich is not in standard Go. return fmt.Errorf("readFile failed: %v", errors.New("file missing")) uses%vwhich formats but does not wrap the error.Final Answer:
return fmt.Errorf("readFile failed: %w", errors.New("file missing")) -> Option DQuick Check:
Use fmt.Errorf with %w to wrap errors [OK]
- Using %v instead of %w for wrapping
- Creating new error string without wrapping
- Using non-standard errors.Wrap function
Ready to prove it?
Pass the test and this pattern moves unknown
