2. GO-Variable parameter functions, anonymous functions and function variables

2. GO-Variable parameter functions, anonymous functions and function variables

2.1. Variable parameter functions

  • Variable parameters means that the number of parameters can be any number
  • The variable parameter must be at the end of the parameter list. Add three dots between the parameter name and the type to indicate the variable parameter function
  • When declaring a function, use the variable parameter as a slice in the function body
package main

import "fmt"

func demo(name string, hover ... string) {
	fmt.Println(name,"My hobby is")

	for i,n := range hover{
		fmt.Println(i,n)
	}
}

func main() {
	demo("derek","reading book","playing ball","game")
}

//result
derek's hobby is
0 reading
1 Playing
2 games

2.2. Anonymous functions

package main

import "fmt"

func main() {
	//The first type: no parameters and no return value
	func(){
		fmt.Println("Anonymous function with no parameters and no return value")
	}()

	//The second type: there are parameters
	func(name string){
		fmt.Println("The name is:",name)
	}("derek")

	//The third type: there is a return value
	name := func() string{
		return "zhang_derek"
	}()
	fmt.Println(name)
}

2.3. Function variables

 Functions are also a type in go language

  •  After defining the tens of thousands of function variables, you can use an anonymous function for assignment, or you can use a defined function for assignment
  • After the function variable is defined, the syntax is the same as that of the ordinary function call. The variable name is the function name of the ordinary function declaration
  • Function variables are the fifth reference type except slice, map, channel, and interface

 (1) The function variable is a reference type

package main

import "fmt"

func b() {
	fmt.Println("bbb")
}

func main() {
	//Function variables are reference types
	var a func()
	a = b
	//The memory address is the same
	fmt.Println(a,b)//0x47d820 0x47d820
}

(2) Function as a parameter

package main

import "fmt"

func mydo(arg func(name string)) {
	fmt.Println("execute mydo")
	arg("derek")
}

func main() {
	mydo(func(name string) {
		fmt.Println(name)
	})
}

(3) Function as return value

package main

import "fmt"

//Function as return value
func a() func() int{
	return func() int {
		return 110
	}
}

func main() {
	result := a()
	r2 := result()
	fmt.Println(r2)//110
}
Reference: https://cloud.tencent.com/developer/article/1481007 2.GO-Variable parameter functions, anonymous functions and function variables-Cloud + Community-Tencent Cloud