Go core development study notes (five) - Pointer

Complex data types:

  1. Pointer pointer
  2. Array array
  3. Structure struct, class alternative
  4. Pipeline channel
  5. Function (also a function type)
  6. Slice slice
  7. Interface interface
  8. map (similar hashmap, set), relatively simple and not complicated, the equivalent of other language map, only this.

Pointer:
all related references relates pointer;
basic data types, variable value is stored, also called value type;
Analysis basic types of data layout in memory.

  • What is a pointer variable:

    package main
    
    import "fmt"
    
    func main() {
    var num int = 200
    fmt.Println(&num)       //num变量的内存地址0xXXXXXXXX
    var ptr *int = &num     //指针变量是num变量的内存地址0xXXXXXXXX,即ptr=&num,ptr数据类型为指针
    fmt.Println(ptr)        //内存地址0xXXXXXXXX
    fmt.Println(*ptr)       //内存地址0xXXXXXXXX对应的值,也就是num变量对应的变量值
    fmt.Println(**&ptr)     //*&ptr相同于ptr,**&prt==*prt,也就是取本内存地址0xXXXXXXXX的变量值
    }
    
  • Changing the stored value in the memory by the pointer variable:

    package main
    
    import "fmt"
    
    func main() {
    var a int = 100       //变量值为100
    var ptr *int = &a     //定义一个指针变量,指向a的内存地址
    *ptr = 200            //将内存地址对应的变量值修改为200
    fmt.Println(a)        //再打印a,对应变量值变为200
    }
    
  • Modify the value of the string pointer:

    package main
    
    import "fmt"
    
    func main() {
    
    var b string = "shit!"
    var ptr1 *string = &b
    *ptr1 = "hit!"
    fmt.Println(b)
    }
    
  • Value types and reference types:

  1. Value Type: basic data types, string, array, struct
  2. Reference types: pointer, slice, map, channel, interface
  • Into the stack area and the heap memory logic: the
    value type is generally in the stack area allocation, variable direct assignment;
    reference type is generally allocated in the heap area, is stored in a variable address, the address corresponding to the real space data storage ( a variable value) when there is no variable references that address, GC becomes waste is recycled
    , since the stack is a logical concept, do not distinguish so detailed, some compilers even the stacks are merged, golang variable according to the length of the life cycle judgment in the end zone on the stack or heap region.
Published 50 original articles · won praise 18 · views 4024

Guess you like

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