What is a pointer?

A pointer is a variable that stores the memory address of another variable. In other words, a pointer “points” to the location in memory where the actual data is stored. Instead of holding the data itself, a pointer holds the memory address of that data.

Pointers are used in many programming languages, including Go, to indirectly access and manipulate data in memory. They are especially useful when you want to avoid copying large amounts of data or when you need to modify the original data without making a copy.

In Go, you can declare a pointer using the * symbol followed by the type of the variable it will point to. To get the memory address of a variable, you use the & operator. To access the value stored at the memory address pointed to by a pointer, you use the * operator.

Here’s a simple example in Go:

package main

import "fmt"

func main() {
    // Declare a variable and assign a value to it.
    var num int = 42

    // Declare a pointer that points to the memory address of the variable.
    var ptr *int = &num

    // Access the value at the memory address pointed by the pointer using the * operator.
    fmt.Println("Value of num:", num)
    fmt.Println("Value pointed by ptr:", *ptr)

    // Modify the value at the memory address through the pointer.
    *ptr = 100
    fmt.Println("Value of num after modification:", num)


Value of num: 42
Value pointed by ptr: 42
Value of num after modification: 100

In this example, we declared a variable num and initialized it with the value 42. We then declared a pointer ptr that points to the memory address of the variable num using the &num syntax. By using the *ptr syntax, we can access the value stored at the memory address pointed to by the pointer, which is 42.

Pointers in Go are particularly useful when you need to pass large data structures to functions efficiently, modify the original data in a function, or when you want to share the same data between multiple parts of a program. However, using pointers requires careful consideration to avoid potential issues like null pointers or memory leaks.

error: Content is protected !!