Previous index: juejin.cn/post/695690…

3. Function types

A function can also be a variable type in Go, that is, a function can be a parameter type or a return value type. The variable type can be printed with %T.

Examples are as follows:

package main
import "fmt"

func add(x,y int) int{
	return x+y
}

func main(a){
	n := add // Declare an add variable
	fmt.Printf("%T\n",n)// Print n is a function that takes two int arguments and returns an int
	fmt.Println(n(1.2)) // add(1,2)
}
Copy the code

Output result:

func(int, int) int
3
Copy the code

Anonymous functions

An anonymous function is a function that has no name. In Go, functions are allowed to be defined while they are being used, but the functions defined inside the function must be anonymous or an error will be reported.

But because an anonymous function does not have a function name, only a function body, you usually need to assign this anonymous function as an argument type to a variable of the function type.

(1) The definition of anonymous function

Func (argument list)(returns argument list){function body}Copy the code

Examples of anonymous functions:

package main
import "fmt"

// Anonymous function
var f1 = func(x,y int) int{
	return x+y
}

func main(a){
	n := f1(1.2)
	fmt.Println(n)
}
Copy the code

Output result:

3
Copy the code

(2) Execute the function immediately

When a function needs to be called only once, arguments can be passed directly after the function definition.

Examples are as follows:

package main
import "fmt"

// Anonymous function
var f1 = func(x,y int) int{
	return x+y
}

func main(a){
	n := f1(1.2)
	fmt.Println(n)

	func(x,y int){
		fmt.Println(x+y)
	}(1.5)// Pass in the values of x and y directly
}
Copy the code

Output result:

3 to 6Copy the code