Array & Pointers in Golang

  • date 22nd March, 2021 |
  • by Prwatech |
  • 0 Comments

A Comprehensive Guide to Pointers in Go

 

In Go (Golang), pointers are variables that store memory addresses, pointing to the location of another value in memory. They allow indirect referencing of values, facilitating efficient memory management and enabling certain advanced programming techniques. Pointers in Go behave similarly to pointers in other languages like C and C++ but with additional safety features provided by Go’s memory management system.

When declaring a pointer variable in Go, the * symbol is used before the type to indicate that the variable is a pointer to that type (e.g., var ptr *int declares a pointer to an integer). Pointers are initialized with the memory address of another variable using the & operator (e.g., ptr = &num assigns the address of num to ptr).

Dereferencing a pointer in Go is done using the * operator (e.g., *ptr retrieves the value stored at the memory address pointed to by ptr). Go also supports pointer arithmetic, although it is generally discouraged for safety reasons.

Understanding pointers in Go is crucial for tasks such as passing references to large data structures, implementing efficient data structures, and interfacing with system-level APIs. Go’s garbage collector helps manage memory automatically, reducing the risk of memory leaks often associated with manual memory management in languages like C.

Prerequisites

Hardware : Local Machine

Software : VS Code, Golang

Open the VS code type the below code.

Creating an array of size 5

Output :

Addition operation in array

Output :

Printing array elements with its positions

Output :

Pointer

Address of a variable

Output :

Assigning values through pointers

Output :

The value of null pointer

Output :

Division using pointer

Output :

0
0

Quick Support

image image