Custom error types in Go - Time & Space Complexity
When creating custom error types in Go, it's important to understand how the program's running time changes as errors are created and handled.
We want to know how the time cost grows when using custom error types compared to simple errors.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type MyError struct {
Msg string
}
func (e MyError) Error() string {
return e.Msg
}
func main() {
err := MyError{"something went wrong"}
fmt.Println(err.Error())
}
This code defines a custom error type and prints its message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the Error() method on the custom error type.
- How many times: Once in this example, but could be multiple times if errors are handled repeatedly.
Each time the Error() method is called, it returns the stored message string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Error(), 10 string returns |
| 100 | 100 calls to Error(), 100 string returns |
| 1000 | 1000 calls to Error(), 1000 string returns |
Pattern observation: The time grows linearly with the number of times the error is accessed.
Time Complexity: O(n)
This means the time to handle errors grows directly with how many times you call the error's method.
[X] Wrong: "Creating a custom error type makes error handling slower in a way that grows faster than the number of errors."
[OK] Correct: Defining a custom error type itself does not add hidden loops or complex operations; the time depends mainly on how often you call its methods.
Understanding how custom error types affect time helps you write clear and efficient error handling code, a skill valuable in many programming tasks.
"What if the Error() method built the message dynamically each time instead of returning a stored string? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of custom error types
Custom error types allow programmers to include more details about what caused the error, beyond just a simple message.Step 2: Compare options with this understanding
Only To add extra information and context to errors correctly describes adding extra information and context. Other options describe unrelated or incorrect behaviors.Final Answer:
To add extra information and context to errors -> Option AQuick Check:
Custom error types add context = B [OK]
- Thinking custom errors fix problems automatically
- Believing custom errors change error printing style
- Assuming custom errors stop errors from returning
Solution
Step 1: Recall how to create custom error types
In Go, a custom error type is a struct that implements the Error() string method.Step 2: Check each option
type MyError struct { msg string } func (e MyError) Error() string { return e.msg } defines a struct and implements Error() correctly. Options A, B, and D do not implement the Error() method properly or define a struct.Final Answer:
type MyError struct { msg string } func (e MyError) Error() string { return e.msg } -> Option CQuick Check:
Custom error = struct + Error() method [OK]
- Defining error as a function without Error() method
- Using string type without Error() method
- Using errors.New instead of custom struct
package main
import (
"errors"
"fmt"
)
type MyError struct {
Code int
}
func (e MyError) Error() string {
return fmt.Sprintf("Error code: %d", e.Code)
}
func main() {
var err error = MyError{Code: 404}
if errors.As(err, &MyError{}) {
fmt.Println("Custom error detected")
} else {
fmt.Println("Unknown error")
}
}Solution
Step 1: Understand errors.As usage
errors.As(err, targetPtr) returns true if err matches the type pointed to by targetPtr.Step 2: Analyze the code's errors.As call
&MyError{} is a pointer to type MyError. err is MyError{Code: 404}, which matches MyError exactly. errors.As succeeds and prints "Custom error detected".Final Answer:
Custom error detected -> Option BQuick Check:
errors.As(MyError, &MyError{}) matches [OK]
- Passing &MyError{} instead of pointer to variable
- Assuming errors.As works with value types
- Confusing errors.Is with errors.As
type MyError struct {
Msg string
}
func (e *MyError) Error() string {
return e.Msg
}
func doSomething() error {
return MyError{Msg: "fail"}
}Solution
Step 1: Check method receiver and returned type
Error() is defined with pointer receiver (*MyError), but doSomething returns a value (MyError), not a pointer.Step 2: Understand interface satisfaction rules
Because Error() has pointer receiver, only *MyError implements error interface, not MyError value. Returning MyError value causes a type mismatch.Final Answer:
doSomething returns MyError value but Error() has pointer receiver -> Option DQuick Check:
Pointer receiver means only pointer type implements error [OK]
- Returning value when method has pointer receiver
- Thinking struct must embed error interface
- Expecting Error() to return int
Solution
Step 1: Check receiver type and error assignment
type CodeError struct { Code int; Msg string } func (e *CodeError) Error() string { return e.Msg } func main() { var err error = &CodeError{Code: 123, Msg: "fail"} var target *CodeError if errors.As(err, &target) { fmt.Println(target.Code) } } uses pointer receiver for Error() and assigns &CodeError{} to err, which matches the pointer receiver.Step 2: Check errors.As usage
type CodeError struct { Code int; Msg string } func (e *CodeError) Error() string { return e.Msg } func main() { var err error = &CodeError{Code: 123, Msg: "fail"} var target *CodeError if errors.As(err, &target) { fmt.Println(target.Code) } } passes &target where target is *CodeError, which is correct usage for errors.As to detect the custom error type.Final Answer:
custom error with pointer receiver and errors.As check -> Option AQuick Check:
Pointer receiver + pointer error + errors.As pointer variable = A [OK]
- Using value receiver but returning pointer or vice versa
- Passing non-pointer target to errors.As
- Assigning value error but using pointer receiver
Ready to prove it?
Pass the test and this pattern moves unknown
