In Go programs, the return
-keyword is used in all methods (except when omitted in ones that return no values). It is possible to return multiple values at once in this language.
With named return values, we can assign to these names to indicate what values we are returning. A return
-statement is still needed to exit the method.
This Go program uses the return
-statement in five separate funcs. The funcs return zero, 1, or more than 1 value in different ways.
return
-keyword.return
-keyword with no argument—or omit return entirely at the method's end.return
-statement.return
-statement can be used on its own.package main import "fmt" // Part 1: can return a single value from a function. func Example1() int { return 10 } // Part 2: can return no value (void method). func Example2() { fmt.Println("Inside Example2") return } // Part 3: can return multiple values that are not named. func Example3() (string, int) { return "bird", 10 } // Part 4: can return multiple named values. func Example4() (name string, count int) { name = "bird" count = 10 return } // Part 5: only the named return values need to be assigned. func Example5() (name string, _ int) { name = "bird" return } func main() { // Invoke the example methods. result := Example1() fmt.Println("Example1", result) Example2() name, count := Example3() fmt.Println("Example3", name, count) name, count = Example4() fmt.Println("Example4", name, count) name, count = Example5() fmt.Println("Example5", name, count) }Example1 10 Inside Example2 Example3 bird 10 Example4 bird 10 Example5 bird 0
It is possible to end a for
-loop with a break
, but often it is possible to use a return instead. This can make the method easier to read—we do not need to look for more statements.
for-range
loop over the elements in the slice, and if an element is greater than or equal to 30, we return. This ends the loop.package main import "fmt" func Example() { // Part 1: use some integers in a slice. numbers := []int{10, 20, 30, 40} // Part 2: loop over the integers, and if we are greater or equal to 30, return. for _, n := range numbers { if n >= 30 { return } fmt.Println(n) } } func main() { Example() }10 20
With the return
-keyword, we can return multiple values. Often Go programs will return a bool
value that tells the caller whether the function succeeded in its task.