Sobes.tech
Junior — Middle

How do the 'return' operator work and what are its limitations in Go?

sobes.tech AI

Answer from AI

In Go, the return operator is used to exit a function and return a value (if the function returns something). It terminates the current function execution and passes control back to the caller.

Features and limitations of return in Go:

  • You can return multiple values, for example:
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}
  • If a function has named return values, you can use return without arguments, which returns the current values of those variables.

  • return cannot be used outside a function — it is a syntax error.

  • After return, no code in the function is executed.

  • In defer functions, you can modify named return values before returning.

Example with named return values:

func sumAndProduct(a, b int) (sum int, product int) {
    sum = a + b
    product = a * b
    return // returns sum and product
}

Thus, return in Go is a simple yet powerful mechanism for exiting a function and returning multiple values.

How do the 'return' operator work and what are its… - sobes.tech