Return Values
A function can send a value back to its caller. For that, declare the data type of the value being returned (int, string and so on) in the function signature, and use the return keyword in the function body.
Return Value Syntax
func FunctionName(param1 type, param2 type) type {
// code to be executed
return output
}
Function Return Example
This myFunction() takes two integers, x and y, adds them (x + y) and returns the sum as an int.
Example
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y int) int {
return x + y
}
func main() {
fmt.Println(myFunction(1, 2))
}
Named Return Values
Go also lets you give a return value a name.
In this example, the return value is called result and has the type int. Because it already has a name, a plain return is enough. Using return without a variable name like this is known as a naked return.
Example
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y int) (result int) {
result = x + y
return
}
func main() {
fmt.Println(myFunction(1, 2))
}
Store the Return Value in a Variable
Rather than printing a function's result directly, you can keep it in a variable for later use.
Example
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y int) (result int) {
result = x + y
return
}
func main() {
total := myFunction(1, 2)
fmt.Println(total)
}
Multiple Return Values
A Go function isn't limited to one return value; it can return several at once.
Example
This myFunction() gives back two values: an integer called result and a string called txt1.
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
fmt.Println(myFunction(5, "Hello"))
}
Example
The two returned values can be assigned to two variables at once, in this case a and b.
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
a, b := myFunction(5, "Hello")
fmt.Println(a, b)
}
Example
Sometimes you only need part of what a function returns. Write an underscore (_) in place of a value you want to leave out. Here it drops the first value.
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
_, b := myFunction(5, "Hello")
fmt.Println(b)
}
Example
This time the underscore takes the second position, so the second returned value (txt1) is ignored.
Output: Go program and captured output
package main
import ("fmt")
func myFunction(x int, y string) (result int, txt1 string) {
result = x + x
txt1 = y + " World!"
return
}
func main() {
a, _ := myFunction(5, "Hello")
fmt.Println(a)
}