Home >Backend Development >Golang >Return value of golang function
Go language functions can use the return statement to return multiple values, which are received by specifying variables after calling the function. The number and type of return values must be explicitly specified in the function declaration, and the function can return any number of values (but cannot return null).
The return value of Go language function
Go language function can use the return
statement to return multiple value. The return value is received through the variable specified in parentheses after calling the function.
Syntax:
func functionName(parameterList) (returnType1, returnType2, ...) { // 函数体 return value1, value2, ... }
Example:
The following function calculates the sum and difference of two numbers:
func calc(a, b int) (sum, diff int) { sum = a + b diff = a - b return }
Practical case:
The following code uses the calc
function to calculate the sum and difference of two numbers entered by the user:
package main import ( "fmt" ) func main() { var a, b int fmt.Print("输入第一个数字: ") fmt.Scanln(&a) fmt.Print("输入第二个数字: ") fmt.Scanln(&b) sum, diff := calc(a, b) fmt.Printf("和:%d\n", sum) fmt.Printf("差:%d\n", diff) }
Description:
return
Each value following the statement corresponds to a return value of the type specified in the function declaration. The above is the detailed content of Return value of golang function. For more information, please follow other related articles on the PHP Chinese website!