One Simple Example To Understand Pointers In Go

Photo by Tim Johnson on Unsplash

One Simple Example To Understand Pointers In Go

Pointers in Go are variables that store the memory address of another variable. They are used to indirectly refer to a value rather than holding the value itself. Here’s a breakdown of pointers in Go:

  1. Pointer Declaration: Pointers are declared using the * symbol followed by the type of the variable it points to. For example, var ptr *int declares a pointer ptr that can point to an integer variable.

  2. Zero Value: If a pointer is declared without initialization, its zero value is nil. This means it does not point to any memory address.

  3. Address of Operator (&): The address of operator & is used to find the memory address of a variable. For example, &variable returns the memory address of variable.

  4. Dereferencing Operator (*): The dereferencing operator * is used to access the value stored at the memory address pointed to by a pointer. For example, *ptr accesses the value pointed to by the pointer ptr.

  5. Pointer Assignment: Pointers can be assigned the memory address of a variable using the address of operator. For example, ptr = &variable assigns the memory address of variable to the pointer ptr.

  6. Pointer Arithmetic: Go does not support pointer arithmetic like some other languages (e.g., C/C++). Operations like adding or subtracting integers from pointers are not allowed in Go.

  7. Pointer Usage: Pointers are commonly used to pass references to data structures between functions without making a copy of the data, which can be more efficient for large data structures. They are also used to modify the value of a variable indirectly.

  8. Memory Management: In Go, memory management is handled by the garbage collector. Pointers can be used safely without worrying about manual memory allocation and deallocation, as in languages like C/C++.

Here’s a simple example to illustrate the usage of pointers in Go:

package main

import "fmt"

func main() {
    var num int = 42
    var ptr *int // declaring a pointer to an integer

    fmt.Println("Value of pointer before assignment:", ptr)
    ptr = &num // assigning the memory address of num to ptr
    fmt.Println("Value of pointer after assignment:", ptr)

    fmt.Println("Value of num:", num)
    fmt.Println("Value of num through pointer:", *ptr)

    *ptr = 100 // modifying the value of num indirectly through pointer

    fmt.Println("Value of num after modification through pointer:", num)
}

/*
Value of pointer before assignment: <nil>
Value of pointer after assignment: 0x1400009c018
Value of num: 42
Value of num through pointer: 42
Value of num after modification through pointer: 100
*/