Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: **Type pointer

Tags:

pointers

go

In tutorial is written:

The type *T is a pointer to a T 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.

pointer memory scheme

What is use of **Type in the Go language?

like image 495
Rudziankoŭ Avatar asked Nov 17 '17 12:11

Rudziankoŭ


People also ask

What is the type of a pointer in Go?

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.

What is the use of * in Golang?

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.

What are Go pointers?

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.

What is the size of a pointer in Go?

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.


1 Answers

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
like image 121
peterSO Avatar answered Sep 29 '22 09:09

peterSO