Naming the Return Values of a Function in Golang
Last Updated :
10 May, 2020
A return value helps to retain the final output of the function after it performs the instructions given in its body. Functions in Golang exhibit variety in return values and rely on the programmer to decide whether to name them or not.
Golang introduces a concept of “Naked Return” allowing the use of return keyword without explicitly stating the return values in the function body provided that the return values are declared in the function header. However, the variable name must be the same as the one defined in the function header.
package main
import "fmt"
func greeting(name string) (message string) {
message = "Hello, " + name
return
}
func main() {
msg := greeting( "GFG" )
fmt.Println(msg)
}
|
Output:
Hello, GFG
Also, the function can return a variable without specifying its name in the function header but only its datatype.
package main
import "fmt"
func greeting(name string) string {
message := "Hello, " + name
return message
}
func main() {
msg := greeting( "GFG" )
fmt.Println(msg)
}
|
Output:
Hello, GFG
A function can also return multiple values and receive multiple parameters. However, to work with a function that returns multiple values, the number of variables that the function returns must be equal to the number of variables that hold the return values when the function execution finishes.
package main
import "fmt"
func operations(a, b int ) (sum, diff, prod, div int ) {
sum, diff, prod, div = a+b, a-b, a*b, a/b
return
}
func main() {
a, b := 5, 3
sum, diff, prod, div := operations(a, b)
fmt.Println(sum, diff, prod, div )
}
|
Output:
8 2 15 1
Share your thoughts in the comments
Please Login to comment...