【Go】pointer | new function | life cycle of variable

1  package main
 2  
3  import (
 4      " fmt " 
5  )
 6  
7  // 1. Each call to f() returns a different result
 8  // 2. Because the pointer contains the address of a variable, if a pointer is used as a parameter Call the function, which will update the value of the variable through the pointer in the function.
9  // 3. Every time we address a variable, or copy a pointer, we create a new alias for the original variable.
10  // 4. For variables declared at the package level, their life cycle is consistent with the running cycle of the entire program.
11  // 5. The declaration cycle of local variables is dynamic: starting from the declaration statement that creates a new variable each time, until the variable is no longer referenced, then the storage space of the variable may be reclaimed. Both the parameter variable and the return value variable of the function are local variables. They are created each time the function is called.
12  // 6. Variables that can be found through package-level variables must be allocated on the heap (escape from the function), escaping variables require additional allocation of memory, and may have a subtle impact on performance optimization.
13  //7. Saving a pointer to a short-lived object into an object with a long-lived period, especially when saving to a global variable, prevents the garbage collection of the short-lived object (and thus may affect the performance of the program). 
14  var p = f()
 15  
16  func main() {
 17      fmt.Println( " ===================== " )
 18      x := 1 
19      p := & x
 20      fmt.Println(p) // 0xc42000e240 
21      fmt.Println( " == update the value of the variable pointed to by the pointer == " )
 22      *p = 2 
23      fmt.Println(x) // 2 
24      fmt.Println( " == equality test between pointers ==" )
 25      var i, j int 
26      fmt.Println(&i == &i, &i == &j, &i == nil) // true false false 
27      fmt.Println( " == Get the local variable v created when the f function is called address == " )
 28      fmt.Println(p)
 29      fmt.Println( " == updating the value of a variable with a pointer == " )
 30      a := 1 
31      incr(&a )
 32      fmt.Println(incr(&a )) // 3 
33  
34      fmt.Println( " ==new()== " )
 35      b := new ( int )
 36      fmt.Println(*b) // 0 
37      *b = 10 
38      fmt.Println(*b) // 10 
39  
40  }
 41  
42 func f() * ​​int {
 43      v := 1 
44      return & v
 45  }
 46  
47 func incr(p * int ) int {
 48      *p++ // Only increment the value of the variable pointed to by p, do not change the p pointer 
49      return * p
 50 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325230881&siteId=291194637