In Go language, you are allowed to return multiple values from a function, using the return statement. Or in other words, in function, a single return statement can return multiple values. The type of the return values is similar to the type of the parameter defined in the parameter list.
Syntax:
func function_name(parameter_list)(return_type_list){
// code...
}
Here,
- function_name: It is the name of the function.
- parameter-list: It contains the name and the type of the function parameters.
- return_type_list: It is optional and it contains the types of the values that function returns. If you are using return_type in your function, then it is necessary to use a return statement in your function.
Example:
package main
import "fmt"
func myfunc(p, q int )( int , int , int ){
return p - q, p * q, p + q
}
func main() {
var myvar1, myvar2, myvar3 = myfunc(4, 2)
fmt.Printf( "Result is: %d" , myvar1 )
fmt.Printf( "\nResult is: %d" , myvar2)
fmt.Printf( "\nResult is: %d" , myvar3)
}
|
Output:
Result is: 2
Result is: 8
Result is: 6
Giving Name to the Return Values
In Go language, you are allowed to provide names to the return values. And you can also use those variable names in your code. It is not necessary to write these names with a return statement because the Go compiler will automatically understand that these variables have to dispatch back. And this type of return is known as the bare return. The bare return reduces the duplication in your program.
Syntax:
func function_name(para1, para2 int)(name1 int, name2 int){
// code...
}
or
func function_name(para1, para2 int)(name1, name2 int){
// code...
}
Here, name1 and name2 is the name of the return value and para1 and para2 are the parameters of the function.
Example:
package main
import "fmt"
func myfunc(p, q int )( rectangle int , square int ){
rectangle = p*q
square = p*p
return
}
func main() {
var area1, area2 = myfunc(2, 4)
fmt.Printf( "Area of the rectangle is: %d" , area1 )
fmt.Printf( "\nArea of the square is: %d" , area2)
}
|
Output:
Area of the rectangle is: 8
Area of the square is: 4
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!