In tutorial is written:
The type
*T
is a pointer to aT
value. The&
operator generates a pointer to its operand.
I am just playing around with pointers in Go and have following:
example := 42
p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int
So if I got it correctly, &p
is a pointer to a pointer to an int value.
What is use of **Type in the Go language?
The Pointer Type. The pointer type in Go is used to point to a memory address where data is stored. Similar to C/C++, Go uses the * operator to designate a type as a pointer. The following snippet shows several pointers with different underlying types.
In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.
Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.
A pointer variable can point to the memory address of any value, and the memory size occupied by the pointer variable is a fixed value, regardless of the size of the value it points to. On a 32-bit machine, the pointer variable occupies 4 bytes, and on a 64-bit machine, it occupies 8 bytes.
Here's a simple demonstration of the concept of a chain of pointers:
package main
import "fmt"
func main() {
i := 42
fmt.Printf("i: %[1]T %[1]d\n", i)
p := &i
fmt.Printf("p: %[1]T %[1]p\n", p)
j := *p
fmt.Printf("j: %[1]T %[1]d\n", j)
q := &p
fmt.Printf("q: %[1]T %[1]p\n", q)
k := **q
fmt.Printf("k: %[1]T %[1]d\n", k)
}
Playground: https://play.golang.org/p/WL2M1jp1T3
Output:
i: int 42
p: *int 0x10410020
j: int 42
q: **int 0x1040c130
k: int 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With