WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Intermediate · question 28 of 100

How do you perform error handling in multiple return value functions in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

Error handling in Go is mainly done using multiple return values, where a function can return both a value (e.g., result of the operation) and an error. The idiomatic way to handle errors in Go is to check for the error immediately after a function call that may return an error.

To illustrate this, let’s suppose we have a function ‘Divide‘ which takes two float64 values and returns the result of the division and an error:

func Divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("Division by zero")
    }
    return a / b, nil
}

In this example, the function ‘Divide‘ has two return values: a float64 representing the result of the division, and an error which represents any errors that occurred during the division operation. The error returned will be ‘nil‘ if no error occurred.

To handle errors in a function that calls ‘Divide‘, you should check for the error immediately after calling the function, like this:

func main() {
    a, b := 10.0, 0.0
    result, err := Divide(a, b)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("The result of %.1f / %.1f is %.1fn", a, b, result)
}

In this example, we call the ‘Divide‘ function and check immediately for the returned error. If the error is not ‘nil‘, we print the error message and return from the ‘main‘ function, otherwise, we continue with the normal operation.

To display the error handling and multiple return values:

  func Divide(a, b float64) (float64, error) {
      if b == 0 {
          return 0, "Division by zero"
      }
      return a / b, nil
  }
  func main() {
      a, b := 10.0, 0.0
      result, err := Divide(a, b)
      if err != nil {
          print("Error:", err)
          return
      }
      print("The result of a / b is result")
  }

In conclusion, error handling in multiple return value functions in Go is done by returning an error as one of the return values and checking for possible errors immediately after calling the function. This way, the error can be handled appropriately before proceeding with further operations.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics