×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Can we return multiple values from a function in Golang?

Learn whether a function can return multiple values or not in Golang?
Submitted by IncludeHelp, on October 05, 2021

The question is, can we return multiple values from a function in Golang?

The answer is – Yes, a Golang function can return multiple values.

Go programming language has built-in support for multiple return values. This feature is used often in idiomatic Go, for example - to return both result and error values from a function.

Consider the below examples.

Example 1:

// Golang program to demonstrate the
// example of returning multiple values
// from a function

package main

import (
	"fmt"
)

// Function to return addition and subtraction
func FindSumAndSub(x, y int) (int, int) {
	return (x + y), (x - y)
}

// Main function
func main() {
	sum, sub := FindSumAndSub(10, 20)
	fmt.Println(sum, ",", sub)

	sum, sub = FindSumAndSub(50, 10)
	fmt.Println(sum, ",", sub)
}

Output:

30 , -10
60 , 40

Example 2:

// Golang program to demonstrate the
// example of returning multiple values
// from a function

package main

import (
	"fmt"
)

// Function to return divide result
// and error
func Divide(x, y int) (int, int) {
	if y != 0 {
		return x / y, 0
	} else {
		return 0, -1
	}
}

// Main function
func main() {
	result, error := Divide(10, 3)
	fmt.Println(result, ",", error)

	result, error = Divide(10, 0)
	fmt.Println(result, ",", error)
}

Output:

3 , 0
0 , -1

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.