DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

Understanding pointers in Go

We define a variable with a value and a name. The variable name will be converted to a memory address and the value gets stored in that address. In case of a pointer variable, an actual memory address of another variable is stored as a value.

The two unary pointer operators.

  • & is used to get the memory address of a variable
  • * is used to get value at the address stored by a pointer variable.

Example:

func main() {
    x := 7
    y := &x // creating a pointer variable

    p := fmt.Println
    pf := fmt.Printf

    pf("type of x (non pointer variable) = %T\n", x)
    p("value of x (stores actual data) =", x)
    p("address of x (memory address where x is located) =", &x)
    // invalid operation: cannot indirect x (variable of type int)
    // p("value dereferenced by x =", *x)

    p()
    pf("type of y (pointer variable) = %T\n", y)
    p("value of y (stores memory address of x) =", y)
    p("address of y (memory address where y is located) =", &y)
    p("value at the address stored by y (dereferencing the pointer) =", *y)
}

Enter fullscreen mode Exit fullscreen mode

Output

type of x (non pointer variable) = int
value of x (stores actual data) = 7
address of x (memory address where x is located) = 0xc00001a0e8

type of y (pointer variable) = *int
value of y (stores memory address of x) = 0xc00001a0e8
address of y (memory address where y is located) = 0xc000012028
value at the address stored by y (dereferencing the pointer) = 7
Enter fullscreen mode Exit fullscreen mode

Resources:

  1. Passing by reference and value in Go to functions
  2. Reference (computer science)
  3. Pointer (computer programming)
  4. Pointer Operators
  5. How are variable names stored in memory in C?

Top comments (3)

Collapse
 
zangassis profile image
Assis Zang

Thanks for sharing it!😀

Collapse
 
danrabbit profile image
danrabbit

Is there any difference between go pointers and C pointers?

Collapse