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: a
the address of the variable is the &a
*
symbol means to take the value of the pointer, such as: *&a
, is a
the value of the address of the variable, of course, a
the value of
simple explanation
*
The sum &
can cancel each other, and note that the sum can *&
be canceled, &*
but the a
sum that cannot be canceled *&a
is the same, both are the value of a, and the value is 1 (because they *&
cancel each other out).
Similarly, the a
sum *&*&*&*&a
is 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 a
and , both are the value of a, *&a
and *b
the value is 1 ( think of it)b
&a
expand again
Because there is, var c **int = &b
the **c
sum **&b
is the same. After you ask the &,
you will find that the **c
sum *b
is the same (it is not difficult to see from here that the *c
sum b
is the same),
and because the sum obtained above is the same, the sum is the same, and the *&a
sum is the same again*b
**c
*&a
. After **c
the appointment a
is 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