Home > Article > Backend Development > What is the return value of golang function?
Go language function return values are typed: function return values must have the specified type. Functions can return multiple values, separated by commas, and can use named return values to improve readability. A function that does not specify a return value type will return a null value (nil).
The return value of Go language function: typing and use
In Go language, a function can return one or more values, which can be of different types. Specifying the type of the return value helps ensure the robustness and readability of your code.
Typed return values
Go language function return values must have an explicit type. This is done by specifying the type after the function name, for example:
func sum(a, b int) int { return a + b }
In this example, the sum
function returns a value of type int
.
Multiple return values
The function can return multiple values, separated by commas, for example:
func divMod(a, b int) (int, int) { return a / b, a % b }
divMod
The function returns a tuple in which the first element is the quotient of integer division and the second element is the remainder.
Named return values
For functions that return multiple values, you can improve readability by using named return values, for example:
func minMax(a, b int) (min, max int) { if a < b { min, max = a, b } else { min, max = b, a } return }
Practical case: Calculating the Fibonacci sequence
The following is a Go language program that uses the return value, which calculates the first n numbers of the Fibonacci sequence:
package main import "fmt" func fib(n int) (int, int) { a, b := 0, 1 for i := 0; i < n; i++ { tmp := a a, b = b, a+b } return a, b } func main() { for i := 0; i < 10; i++ { fmt.Printf("%d\n", fib(i)) } }
Output:
0 1 1 2 3 5 8 13 21 34
Note:
nil
). void
, this needs to be specified explicitly, for example: func foo() void
. The above is the detailed content of What is the return value of golang function?. For more information, please follow other related articles on the PHP Chinese website!