Go Pointers

What is a Pointer?

A pointer is a variable that stores the memory address of another variable.

Instead of storing a value directly, it points to where the value is stored in memory.

Loading...
Output:

The Address Operator (&)

The & operator is used to get the memory address of a variable.

This is how you create a pointer in Go.

Loading...
Output:

Dereferencing (*)

The * operator is used to access the value stored at a pointer’s address.

This is called dereferencing.

Loading...
Output:

Modifying Values with Pointers

One of the most important uses of pointers is modifying a variable through its memory address.

Changing the value using the pointer also changes the original variable.

Loading...
Output:

Pointers in Functions

By default, Go passes values to functions (pass-by-value).

Using pointers allows functions to modify the original variable.

Loading...
Output:

Pointer Types

A pointer has a type based on what it points to.

For example, *int is a pointer to an integer.

Loading...
Output:

Why Use Pointers?

Pointers are essential in Go for performance and memory efficiency.

  • Avoid copying large data
  • Allow functions to modify variables
  • Used heavily with structs and methods

Common Mistakes

Be careful when working with pointers:

  • Dereferencing a nil pointer will cause a runtime error
  • Forgetting * when accessing values
  • Confusing value vs address
Loading...
Output:

Practice

Create a function that takes a pointer to an integer and doubles its value.

Loading...
Output:

Need Help?