DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

3 1 1 1 1

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?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay