* and & of pointer symbols in go language

Look at a piece of code

Put a piece of code first, run it manually, and see how many questions you can get right?

package main

import "fmt"

func main() {
    var a int = 1
    var b *int = &a
    var c **int = &b
    var x int = * b
    fmt.Println("a = ",a)
    fmt.Println("&a = ",&a)
    fmt.Println("*&a = ",*&a)
    fmt.Println("b = ",b)
    fmt.Println("&b = ",&b)
    fmt.Println("*&b = ",*&b)
    fmt.Println("*b = ",*b)
    fmt.Println("c = ",c)
    fmt.Println("*c = ",*c)
    fmt.Println("&c = ",&c)
    fmt.Println("*&c = ",*&c)
    fmt.Println("**c = ",**c)
    fmt.Println("***&*&*&*&c = ",***&*&*&*&*&c)
    fmt.Println("x = ",x)
}

 

explain

 

theory

&Symbol means to take the address of the variable, such as: athe address of the variable is the &a 
*symbol means to take the value of the pointer, such as: *&a, is athe value of the address of the variable, of course, athe value of

 

simple explanation

*The sum  & can cancel each other, and note that the sum can *&be canceled, &*but  the
asum that cannot be canceled *&ais the same, both are the value of a, and the value is 1 (because they *&cancel each other out). 
Similarly, the asum *&*&*&*&ais the same, both are 1 (because the 4 *&cancel each other out)

 

expand

Because there  is,
var b *int = &a 
it  is the same as
aand , both are the value of a, *&aand *bthe value is 1 ( think of it)b&a

 

expand again

Because there  is,
var c **int = &b 
the 
**csum **&bis the same. After you ask the &, 
you will find that the **csum *bis the same (it is not difficult to see from here that the *csum bis the same), 
and because the sum obtained above is the same, the sum is the same, and the  *&asum is  the same again*b

**c*&a
. After
**cthe appointment  ais the same, both are 1

Do not believe you try?

 

Announce results

The address value (starting with 0xc200) in the result of the operation may be different for different machines, you know

$ go run main.go
a      =     1
&a     =     0xc200000018
*&a    =     1
b      =     0xc200000018
&b     =     0xc200000020
*&b    =     0xc200000018
*b     =     1
c      =     0xc200000020
*c     =     0xc200000018
&c     =     0xc200000028
*&c    =     0xc200000020
**c    =     1
***&*&*&*&c     =     1
x      =     1

 

Two-symbol cancellation order

*&Can be cancelled at any time, but &*cannot be cancelled because the order is wrong

fmt.Println("*&a\t=\t",*&a) //Successfully offset, print 1, which is the value of a
fmt.Println("&*a\t=\t",&*a) //Cannot be offset, an error will be reported

Guess you like

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