当前位置:网站首页>Golang learning notes - pointer

Golang learning notes - pointer

2022-06-21 21:04:00 Sentiment.

C I have never learned the pointer of , Happen to happen Golang There is a by-pass look inside .

The pointer

Go The function parameters in the language are all value copies , When we want to modify a variable , We can create a pointer to the address of the variable . Passing data using pointers , Without copying data .

The difference in C The pointer to ,Golang The middle pointer cannot be offset and operated

Two symbols :&( Address fetch )、*( According to the address )

grammar

A memory address that points to a value .

Similar to variables and constants , You need to declare a pointer before you use it . Format :

var var_name *var_type

Demo01

package main

import "fmt"

func main() {
    
   var p *int
   fmt.Printf("p:%v\n", p) // Default to when not assigned nil
   fmt.Printf("p:%T\n", p) // The type is *init

   a := 100
   p = &a                //& take a The address of 
   fmt.Printf("%v\n", p) //p Direct output address 
   fmt.Printf("%v", *p)  //*p Output the value corresponding to the address 

}

result :

p:<nil>
p:*int
0xc00000a0c0
100

Array pointer

grammar

var var_name [MAX]*int;

Demo02

package main

import "fmt"

func main() {
    
   a := [3]int{
    1, 2, 3}
   var p [3]*int
   fmt.Printf("p:%v\n", p) // Default to when not assigned nil

   for i := 0; i < len(a); i++ {
    
      p[i] = &a[i]
   }
   fmt.Printf("p:%v\n", p) // After assignment, the address is output 

   for i := 0; i < len(p); i++ {
    
      fmt.Printf("%v ", *p[i]) // Get the value of the corresponding address 
   }
}

result :

p:[<nil> <nil> <nil>]
p:[0xc000014150 0xc000014158 0xc000014160]
1 2 3 

You can also calculate the address through the pointer

package main

import (
   "fmt"
   "unsafe"
)

func main() {
    

   p := [3]int8{
    1, 2, 3}
   //1. Get the address pointer of the first element of the array 
   var f = &p[0]
   //2. convert to Pointer type 
   ptr := unsafe.Pointer(f)

   //3. convert to uintptr type , Then calculate the memory address ( Address plus a byte , It means taking the value of the second index )
   targetAddress := uintptr(ptr) + 1
   //4. According to the new address , Convert it back to Pointer type 
   newPtr := unsafe.Pointer(targetAddress)
   //5.Pointer Object conversion to int8 Pointer types 
   value := (*int8)(newPtr)
   fmt.Println(*value)

}
原网站

版权声明
本文为[Sentiment.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211920166873.html