简体   繁体   中英

What's the meaning of '&i' when i := &b

I'm learning the go, I tried the '&' to get the memory address.But I werid that what's the meaning of '&i',and 'i' came from i := &b , b is a int.

b := 7
i := &b
fmt.Println(&b) //print => 0xc000088000
fmt.Println(i) //print => 0xc000088000
fmt.Println(&i) //print => 0xc00000e018

In this case , What's the meaning of '&i'?

& is the address operator , evaluating it results in a memory address, which when passed to the fmt package, usually the memory address is printed in hexadecimal format ("base 16 notation, with leading 0x").

A memory address is just that: a memory address. It doesn't matter if it's an address of an int variable or a string , or a variable of a pointer type. When printed, they all look the "same".

The address operator:

For an operand x of type T , the address operation &x generates a pointer of type *T to x .

So the address operator gives you a pointer value which when you dereference, you get back the original value.

&b will be an address of the variable b , of type *int , which when you dereference: *b will give you (the value of) b .

&i will be the address of the variable i , of type **int , which when you dereference: *i will give you the value of i which is the address of b . So if you also dereference that: **(&i) , that will also give you (the value of) b .

Here &b returns address of b and the same address is stored in i . Since i is also a variable &i will return the address of variable i.

So & operator generates a pointer to it's operand. So &i basically generates a pointer to i which is already a pointer to b which is nothing but a memory address. So when you do fmt.Println(&i) it prints the memory address of i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM