Function definition rules: Function name, parameter list, return value type are clear Function call: Function name actual parameter list, actual parameter order and type correspond to actual case: Calculate the sum of two numbers and find the factorial of a number Parameter transfer: value Passing, modifying the parameter value within the function does not affect the external value of the function. The variable parameter is placed at the end of the parameter list, using... to represent
In Go language, the syntax of function definition is as follows:
func 函数名(参数列表) 返回值类型 {...}
Function name
: The name of the functionParameter list
: The parameter list of the function, the parameter type and order must be clearReturn value type
: The return value type of the function, there can be multiple or no return values Function call uses the following syntax:
函数名(实参列表)
Actual parameter list
: The actual parameter list of the function, required Corresponds to the order and type of the parameter list defined by the function// 定义一个函数计算两个数之和 func add(a, b int) int { return a + b } // 函数调用 result := add(10, 20) fmt.Println(result) // 输出 30
// 定义一个函数计算一个数的阶乘 func factorial(n int) int { if n == 0 || n == 1 { return 1 } return n * factorial(n-1) } // 函数调用 result := factorial(5) fmt.Println(result) // 输出 120
Function parameter passing in Go language adopts value passing. This means that modifying parameter values within the function body will not affect values outside the function. For example:
func changeValue(num int) { num = 100 } // 函数调用 num := 20 changeValue(num) fmt.Println(num) // 输出 20
The parameter list of the function can use ...
to represent variable parameters. Variable parameters must be placed at the end of the parameter list. For example:
func sum(nums ...int) int { sum := 0 for _, num := range nums { sum += num } return sum } // 函数调用 result := sum(1, 2, 3, 4, 5) fmt.Println(result) // 输出 15
The above is the detailed content of Detailed explanation of Golang function definition and calling rules. For more information, please follow other related articles on the PHP Chinese website!