Go Function Return Multiple Values

1. Introduction

Go has the ability to return multiple values from a function. This feature can be particularly useful when you want to return both result data and an error value from a function, which is a common pattern in Go programs.

Definition

A function in Go can return any number of results by listing them in its return type. When calling such a function, you can handle each returned value separately.

2. Program Steps

1. Define a function that returns multiple values.

2. Call this function and handle its multiple return values.

3. Use the blank identifier to ignore one or more returned values.

3. Code Program

package main

import (
	"errors"
	"fmt"
)

// divide divides two integers and returns the result and error if any.
func divide(x, y int) (int, error) {
	if y == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return x / y, nil
}

func main() {
	// Step 2: Call the function that returns multiple values
	result, err := divide(10, 2)

	// Handle the multiple return values here
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Result of division:", result)
	}

	// Step 3: Ignore a value using the blank identifier
	_, err = divide(10, 0)
	if err != nil {
		fmt.Println("Error:", err)
	}
}

Output:

Result of division: 5
Error: cannot divide by zero

Explanation:

1. package main and import statements are used to declare the package and import necessary packages.

2. The divide function takes two int parameters and returns two values: an int result and an error.

3. When divide is called with y as 0, it returns an error which is then handled in the main function.

4. When the division is successful, the result is printed.

5. The blank identifier _ is used when calling divide to ignore its result value.

6. The output shows both the successful division operation and the handling of an error case when division by zero is attempted.

In this example, we will show you how to write a function in Go to return multiple values.

Go functions allow to return of multiple values.

Example 2

In the example, we have a threerandom() function, which returns three random values.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func threerandom() (int, int, int) {

    rand.Seed(time.Now().UnixNano())
    x := rand.Intn(10)
    y := rand.Intn(10)
    z := rand.Intn(10)

    return x, y, z
}

func main() {

    r1, r2, r3 := threerandom()

    fmt.Println(r1, r2, r3)
}

Output:

0 8 7


Comments