python to go learning notes -- functions

function

//Basic grammar
func Function name (parameter list ) (Return value list) {
    Function body
}
  1. The naming rules of functions follow the identifier naming standard. Functions with uppercase letters can be used by this package file and other files, similar to public; Files with lowercase initials can only be used by this package, which is similar to private (equivalent to single and double underline functions in python object-oriented);
  2. The go function does not support overloading.
  3. Function in golang is also a data type, which can be assigned to variable, which can call function
func getSum(n1 int ,n2 int) int {
	return n1 + n2
}

func main() {
	a := getSum
	fmt.Printf("a The type of is%T,getSum The type of is%T\n",a,getSum)

    res := a(10,20)		// Equivalent to a: = getsum (10,20)
	fmt.Println(res)
}
//The type of a is func(int, int) int, and the type of getsum is func(int, int) int
//30
  1. The go function can be called as a formal parameter
func getSum(n1 int ,n2 int) int {
	return n1 + n2
}

func mydef(def func(int,int) int,num1 int ,num2 int) int {
	return def(num1,num2)
}
func main() {
	res2 := mydef(getSum,10,20)
	fmt.Println(res2)
}
  1. Support function return value naming
func cal(n1 int) (n2 int) {
    n2 = n1 + 1
    return
}
  1. Custom data type
func main() {
	type myInt int // Alias int
	var num1 myInt = 40
	var num2 int
	num2 = int(num1)	// Although they are all int types, they still need to be converted
	fmt.Printf("%T,%d",num1,num2)
    
    type mydefType func(int,int) int //mydefType is equal to func(int,int) int type
}
  1. Support variable parameter args (equivalent to * args in python, * * kwargs: * indicates' tuple 'type, * * indicates' dict' type)
func sum(n1 int,args... int) int {
	sum := n1
    //Traversal args name doesn't matter, anything (in accordance with the naming convention)
	for i:= 0;i<len(args);i++ {
		sum += args[i]	// args is the slice type
	}
	return sum
}

func main() {
	fmt.Println(sum(1,1,2,3,45,65))
}
//117

return statement

Return has several small details. The go function can return multiple values (python can also, but C/java can't), but when go returns multiple values, if you want to ignore a value when receiving, you can use_ To ignore; When there is only one return value, you can not write ().

func cal(n1 int ,n2 int) (sum int,sub int) {
	sum = n1 + n2
	sub = n1 - n2
	return
}
func main() {
	res,_ :=cal(20,10)
	fmt.Println(res)
}
init function

Similar to the construction method in java, the instantiation object in python. The init function is called before the main function

var Age int
var Name string

func init()  {
	Age = 18
	Name = "flandre"
}

If a go file contains global variables, init function and main function at the same time. The execution process defines = = > init function = = > main function for global variables.

Anonymous function

It's lambda in python.

func main() {
	// Called directly when defining anonymous functions
	res := func(n1 int,n2 int) int {
		return n1+n2
	}(10,20)
	fmt.Println(res)
	// Assign anonymous functions directly to variables, and then call a.
    lambda := func(n1 int,n2 int) int {
		return n1+n2
	}
	res2 := lambda(10,20) 
	fmt.Println(res2)
}
//30
//30

Global anonymous functions are valid in the whole world

var (
	Fun1 = func(n1 int,n2 int) int {
		return n1*n2
)
closure

Function nest function (python is like this)

func AddUpper() func(int) int {
	var n int = 10
	return func(x int) int {
		n = n + x
		return n
	}
}

func main() {
	f := AddUpper()
	fmt.Println(f(1))		// 11
	fmt.Println(f(2))		// 13
}
defer

A delay mechanism. When it is executed to defer, the code statement will be pressed on the stack, and the function will be executed after execution, so the lowest defer code will be output first

func main() {
	//The defer keyword is in the form of stack pressing, and end2 is output first
	defer fmt.Println("main end1")
	defer fmt.Println("main end2")

	fmt.Println("main::hello go 1")
	fmt.Println("main::hello go 2")
}
//main::hello go 1
//main::hello go 2
//main end2
//main end1

When defer puts the statement on the stack, it will also copy the relevant values and put them on the stack at the same time

func sum(n1 int ,n2 int) int {
	defer fmt.Println("n1 = ",n1)			// n1 = 10
	defer fmt.Println("n2 = ",n2)			// n2 = 20
	res := n1 + n2							// res = 30
	n1++									// n1 =11
	fmt.Println("res = ",res ,"n1 = ",n1)	// res=30 n1=11
	return res
}

func main() {
	sum(10,20)
}
//res =  30 n1 =  11
//n2 =  20
//n1 =  10

defer is mainly used to release the resources created by the function. The simulation code is as follows:

func test() {
	//Free file resources
	file = openfile(file name)
	defer file.close()
    //Release database resources
    connect = openDatabase()
	defer connect.close()
}
Parameter transfer
  • Value transfer: the larger the data, the lower the efficiency.
  • Reference delivery: copy of address with small amount of data.
func test_print(num *int) {
	print(*num)
}

func main() {
	num := 20
	test_print(&num)
}

Keywords: Python Go

Added by yanjchan on Wed, 23 Feb 2022 04:31:22 +0200