ADVERTISEMENT
ADVERTISEMENT

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 »

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.