0
0
Goprogramming~5 mins

Custom error types in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom error types
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time the Error() method is called, it returns the stored message string.

Input Size (n)Approx. Operations
1010 calls to Error(), 10 string returns
100100 calls to Error(), 100 string returns
10001000 calls to Error(), 1000 string returns

Pattern observation: The time grows linearly with the number of times the error is accessed.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle errors grows directly with how many times you call the error's method.

Common Mistake

[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.

Interview Connect

Understanding how custom error types affect time helps you write clear and efficient error handling code, a skill valuable in many programming tasks.

Self-Check

"What if the Error() method built the message dynamically each time instead of returning a stored string? How would the time complexity change?"