Go core development study notes (13)! - function call mechanism, recursive

Method: completion code or a set of functions.
General process: methods necessary to input, the method returns the result.

Function call mechanism underlying Analysis:
stack area : basic data types are generally assigned to the stack area, there is an escape analysis compiler.
Heap : General reference data types assigned to the heap region, there is an escape analysis compiler.
Area codes : code storage memory area

By calling a procedure, function calls have a deep understanding of what has been done:

package main
import "fmt"

func calcu (a float64,b float64) (float64,float64) {
	
	plus := a + b
	minus := a - b
	return plus,minus
}
func main() {
	/*
	第一步 main是一切程序的入口,首先现在内存栈区开辟一块空间存储变量
	      a=5 b=3 都是基本变量,一般存在内存栈区
	 */
	var (
		a float64 = 5
		b float64 = 3
	)
	/*
	第二步 调用函数,将两个变量的值传入函数中,系统在内存栈区开辟另一块儿空间放入被调用函数,
	       这个地方的函数的内存与main程序的内存空间完全是两个用户空间,这也就是说为何被调用函数如果
	       没有返回值,就是两个完全不相干的函数调用,也就失去了调用意义,调用结束返回后,return结束
	       被调用函数,并且返回值,编译器就会将这部分垃圾回收,回到main()中继续走完
	 */
	max, min := calcu(a,b)
	
	/*
	第三部 执行接下来main中的其他语句,直到执行完成后,编译器回收所有占据内存的垃圾。
	 */
	fmt.Println(max)
	fmt.Println(min)
}

Recursive function calls

  1. A function in the body of the function itself calls itself is recursive call.
  2. Case:

main Package
Import "FMT"
FUNC recu (n-float64) {
IF n-> 2 {
N-
recu (n-) // iteration inside recu recu (), each iteration successful cross section has a separate user space from each other variables influences.
The else {}
fmt.Println ( "n-=", n-)
} // end until the function has no return value, so no new value generating
}
FUNC main () {
var A = float64. 4
recu (A) // not any return value, so the next after the call does not produce any output
}

  1. Recursive always want to terminate the recursion conditions infinitely close to, or is infinite recursion, infinite loop.

  2. When a function is finished, or encountered return, will return, who comply with the call returns to whom, and when the function is finished or return, the system function itself will be destroyed, no longer occupy memory space.

  3. Recursive call Exercise: recursively calculated using Fibonacci number, to the n-th random integer, find the number of columns of value is how much?

    package main
    import "fmt"
    func fbnq(n int) int {
    
    	if n == 1 || n==2 {
    		return 1
    	} else {
    		return fbnq(n-1) + fbnq(n-2)
    	}
    }
    func main() {
    	res := fbnq(6)
    	fmt.Println(res)
    }
    
  4. Function value, known f (1) = 3, f (n) = 2 * f (n) + 1, when n assigned to one obtains f (n) should be?

    package main
    import "fmt"
    func f(n int) int {
    
    	if n == 1 {
    		return 3
    	} else {
    		return 2*f(n-1) + 1
    	}
    }
    
    func main() {
    	res := f(6)
    	fmt.Println(res)
    }
    
  5. Monkey eating peaches, the first day eat half of the peaches, then eat one tenth day found only a peach, seeking a total of how many peaches

    package main
    import (
    	"fmt"
    )
    func f(n int) int {
    
    	if n == 10 {
    		return 1
    	} else {
    		return (f(n+1) + 1) * 2      //其实这个else有问题,需要限定范围,1<n<10
    	}
    }
    
    func main() {
    	res := f(1)
    	fmt.Println(res)
    }
    

Note discuss the details of function and
8. The parameter list may be plural, the returned list may be plural, the plurality of return value of the brackets must be added.
9. The parameter lists and return value data type may be a list of value types may be used type.
10. The first letter of the function name can not be a number, because the first letter of the case decided whether the function is invoked other packages, so like to understand, similar to java's capital public, lowercase is private.
11. The scope function: the function is a local variable, external function does not take effect, a function corresponding to a user space.
12. The basic data types and arrays default values are passed, in the modified function, it will not affect the original value.
Or understand the value of copies, and will not affect the value of the calling function itself.

13. If you want to change the variable function by external variables within the function, the address of the variable & can pass, the function pointer in a variable manner, that is passed by reference in the main impact on the values.

**举例值传递,函数在变量+10后,并不会影响主函数中n值不变。**
```
package main                                               
import "fmt"
func test(n int) int {                               
	n = n + 10                           
	fmt.Println("test n = ",n)                 
	return n               
}
func main() {
	var n int = 10
	test(n)
	fmt.Println("main n = ",n)
}                                // main n=10
```

**举例指针传递,函数在指针取值后,影响到主函数中的n,使n+10变为了20:**
```
package main
import "fmt"
func test1(n *int) int {
	*n = *n + 10
	fmt.Println("test n = ",*n)
	return *n
}
func main() {
	var n int = 10
	test1(&n)
	fmt.Println("main n = ",n)
}                                //main n=20
```
  1. Golang not support traditional function overloading, allowed two functions with the same name exists, even if the number of different parameter too.

  2. Golang also a function of the data type can be assigned to a variable that is a function of the type of a variable, a function can be called by the variable, the variable will be appreciated that facilitate memory functions to a function add = alias variables, the function () no problem, then the variable () no problem.

  3. Functions can also do arguments to the call,

    package main
    import "fmt"
    func getSum (n1 int,n2 int) int {
    	return n1 + n2
    }
    func ff (ff func(int,int) int, num1 int, num2 int) int {     // ff类型为函数类型,与getSum一致,再传 n1 ,n2 形参, 再返回一个int返回值
    	return ff(num1 , num2)
    }
    
    func main() {
    	res2 := ff(getSum,10,20)
    	fmt.Println(res2)
    }
    
  4. To simplify the data type definitions, Go supports custom data types: type corresponds to Myint // int int added aliases , var xx myint (actually int)
    is preferably wording is treated as a function of parameter, type myfunc FUNC (int, int) int // myfunc type corresponds to a dual function return type single parameter

  5. Support function returns the value of the named: func when the return value definition defined func (n1 int, n2 int) (sum int, sub int) {...} // This will return two values are defined directly, there is no sequence of points a. Finally, this function only needs to return, and do not need to add any return.

  6. Two more return value can be used _ ignored , I just want to get one, do not want other.

  7. Go supports variable parameters, e.g. func getSum (args ... int) ( sum int) {...} // args ... seven bytes are indispensable, 0 to pass a plurality of parameters.
    func getSum (n1 float64, args ... int) (sum int) {...} // pass a float64, pass 1 to the plurality of parameters int
    args is a slice, the respective values can be accessed by args [i], it is understood to dynamic arrays.

    Case: For func getSum (args ... int) (sum int) {...} how to pass parameters:

    package main
    import "fmt"
    func get1Sum (n1 int, args... int)  int {      //args可以变成其他的字符,vars也可以,但是一般约定俗成,不要乱改。
    	sum := n1                                  //可变参数args一定要放在形参列表里的最后
    	for i := 0 ; i < len(args) ; i++ {
    		sum += args[i]
    	}
    	return sum
    }
    func main() {
    	res := get1Sum(1,2,3,4,5)
    	fmt.Println(res)
    }
    
Published 50 original articles · won praise 18 · views 4016

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/89684168