Golang learning road-init function, anonymous function, closure

init function

1. Basic introduction

Each source file can contain an init function, which will be called by the Go runtime framework before the main function is executed, which means that init will be called before the main function.

2. Case description

package main
import "fmt"
 
//init函数,通常可以在init函数中完成初始化工作
func init(){
    
    
	fmt.Println("init()...")
}

func main(){
    
    
	fmt.Println("main()...")
}

operation result:
Insert picture description here

3. Precautions for init function

1. If a file contains global variable definitions, init function and main function at the same time, the execution flow is: global variable definition-"init function-"main function.

package main
import "fmt"
 
var age  = test()
//init函数,通常可以在init函数中完成初始化工作
func init(){
    
    
	fmt.Println("init()...")
}

func test() int{
    
    
	fmt.Println("test()...")
	return 20
}
func main(){
    
    
	fmt.Println("main()...")
}

Operation result:
Insert picture description here
2. Interview question: Case If both main.go and utils.go contain variable definitions, what is the execution flow of the init function?
See below:
Insert picture description here

Anonymous function

1. Basic introduction

Go supports anonymous functions. An anonymous function is a function without a name. If we only want to use a function once, we can consider using an anonymous function. An anonymous function can also be called multiple times.

2. How to use anonymous functions

Way 1

When the anonymous function is defined, it is called directly. In this way, the anonymous function can only be called once.

package main
import "fmt"
 
func main(){
    
    
	
	res := func(n1 int ,n2 int) int {
    
    
		return n1 + n2
	}(10,30)
	fmt.Println("res =",res)
}

operation result:
Insert picture description here

Way 2

Assign the anonymous function to a variable (function variable), and call the anonymous function through the variable.

package main
import "fmt"
 
func main(){
    
    
	
	
	a := func(n1 int, n2 int) int{
    
    
		return n1 + n2
	}
	res := a(10,20)
	fmt.Println("res =",res)
}

operation result:
Insert picture description here

3. Global anonymous functions

If an anonymous function is assigned to a global variable, then this anonymous function becomes a global anonymous function and can be effective in the program.

package main
import "fmt"

var (
	Fun = func(n1 int, n2 int) int{
    
    
		return  n1 + n2
	}
)
 
func main(){
    
    
	
	//全局匿名函数的使用
	res := Fun(15, 10)
	fmt.Println("res =",res)
}

operation result:
Insert picture description here

Closure

1. Introduction to closures

A closure is a combination of a function and its related reference environment as a whole.

2. Case demonstration

package main
import "fmt"

//累加器
func add() func (int) int{
    
    
	var n int = 10
	return func(x int) int{
    
    
		n = n + x
		return n
	}
}
 
func main(){
    
    
	
	f := add()
	fmt.Println(f(1))
	fmt.Println(f(2))
	fmt.Println(f(3))

}

Operation result:
Insert picture description here
Description:

  1. add is a function, and the returned data type is fun (int) int

  2. Insert picture description here
    What is returned is an anonymous function, but this anonymous function refers to n outside the function, so this anonymous function forms a whole with n, forming a closure.

  3. It can be understood like this: a closure is a class, a function is an operation, n is a field, and a function and its use of n constitute a closure.

  4. When we call the f function repeatedly, because n is initialized once, it is accumulated every time it is called.

  5. The key to understanding closures is to analyze which variables are used (referenced) by the returned function, because the function and the variables it references together constitute a closure.

3. The practice of closure

Write a function makeSuffix(suffix string) to receive a file suffix (such as .jpg) and return a closure. Call the closure, you can pass in a file name, if the file name does not have a specified suffix (such as .jpg), the file name .jpg is returned, if there is already a .jpg suffix, the original file name is returned. Requires the use of closures to complete.
Code:

package main
import (
	"fmt"
	"strings"
)

func makeSuffix(suffix string) func (string) string{
    
    

	return func (name string) string{
    
    
		if !strings.HasSuffix(name,suffix){
    
    
			return name + suffix
		}
		return name
	}
}
 
func main(){
    
    
	
	f := makeSuffix(".jpg")
	fmt.Println("文件名处理后=",f("abc"))
	fmt.Println("文件名处理后=",f("zxy.jpg"))

}

Operation result:
Insert picture description here
Explanation:
1. The returned anonymous function and the suffix variable of makeSuffix (suffix string) are combined into a closure, because the returned function refers to the variable suffix.
2. Let's experience the benefits of closures. If you use traditional methods, you can easily implement this function, but traditional methods need to pass in the suffix name every time, such as jpg, and closures can retain one of the last quoted Value, so we can pass it in once and use it repeatedly. Everyone can experience it carefully!

Guess you like

Origin blog.csdn.net/weixin_44736475/article/details/113941510