go language --- special types of functions

init function

Mainly to complete the initialization work, the
init function can be defined in each file. During the execution, the init function is executed first, and the main function is executed

Insert picture description here
note

  • If a file contains global variables, init functions, and main functions at the same time, the execution process is the definition of global variables—>init function—>main function
    Insert picture description here

Anonymous function

Go language supports anonymous functions. If we only want to use some functions once, we can consider using anonymous functions. Anonymous functions can also be called multiple times

Use of anonymous functions

  • When defining an anonymous function, call it directly.This function can only be used once
func main(){
    
    
	//在定义的时候直接调用
	res := func (n1,n2 int)int{
    
    
		return n1 + n2
	}(10,20)	//直接传参调用

	fmt.Println("res = ",res)
}
  • Assign an anonymous function to a variable, and call it through the variable
a := func (n1,n2 int)int{
    
    
	return n1 - n2
}

res := a(10,20)
fmt.Println("res = ",res)

We assign the anonymous function to a function variable, at this time, we can complete multiple calls through the function variable

  • Global anonymous function, assign an anonymous function to a global variable, then the function can be accessed anywhere in the file.
var (
	Func1 = func (n1 int,n2 int)int {
    
    
		return n1 + n2
	}
)

res3 := Func1(10,20)
fmt.Println("res3 = ",res3)

Defer function

In the function, some resources are often used, such as (database, file operation, etc.). In order to release the resources in time after the function execution ends, the defer function appears, which is similar to the smart pointer in C++.

Function characteristics:

  • When the defer-modified statement is executed, the statement is pushed onto the stack first.
  • When the function ends, pop data from the defer stack in turn
func sum(n1 , n2 int) int {
    
    
	defer fmt.Println("n1 = ",n1)
	defer fmt.Println("n1 = ",n1)
	res := n1 + n2
	fmt.Println("res = ",res)
	return res
}

Insert picture description here
Insert picture description here

The statements that are pushed onto the stack first are executed, and the statements that are pushed onto the stack later are executed first.

Advantages of the defer function: When
Insert picture description here
we apply for some more resources, we can prevent the later forgetting to release and cause resource leakage. Therefore, after we apply for the resources, we can write the defer function immediately. When the function runs, the defer function automatically releases the requested resource.

Guess you like

Origin blog.csdn.net/qq_42708024/article/details/106908931