This is a created article in which the information may have evolved or changed.
The basic composition of the function:
- The keyword func
- Name of function
- Parameter list
- return value
- function body
- Return statement
The GO function does not support overloading, default parameter values, variable length arguments, multiple return values, and so on.
func main() { /* 定义局部变量 */ var a, b = 4, 5s := add(a,b)fmt.Println(s)}func add(a, b int) int {return a + b}
Note: A function that starts with a lowercase letter is visible only within this package, and a function that begins with a capital letter can be used by another package.
Indefinite parameter type function: The number of arguments passed in by the function is variable
func main() {myFunc(1,2,3)}func myFunc(args ...int) {for _,arg := range args {fmt.Println(arg)}}
Anonymous functions (a function implementation that does not need to define function names)
An anonymous function consists of a function and function body without a function name, which can be directly assigned to a variable or executed directly.
f := func(a, b int) int {return a * b}
Closed Package