Can you return multiple values from a function?

Yes, you can return multiple values from a function in Go. Go allows functions to return multiple values, making it convenient for functions to provide different types of information or results without the need for complex data structures like tuples.

To return multiple values from a function, you simply need to specify the return types separated by commas in the function signature. Here’s an example:

package main

import "fmt"

func divideAndRemainder(a, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder

func main() {
    result1, result2 := divideAndRemainder(17, 5)
    fmt.Println("Quotient:", result1)
    fmt.Println("Remainder:", result2)

In this example, the divideAndRemainder function takes two integers as input and returns two integers (the quotient and remainder) as output. When calling the function, we use two variables result1 and result2 to capture the returned values.


Quotient: 3
Remainder: 2

You can return any number of values from a function, and the caller can capture them using multiple variables. This feature is frequently used in Go to handle different return scenarios and error handling elegantly. For example, a function may return both a result and an error value to indicate success or failure.

Keep in mind that it’s essential to provide meaningful variable names for the returned values to improve code readability and maintainability.

error: Content is protected !!