Go from Beginner to Expert: A Complete Guide to Learn Golang PART-15

Step-by-Step Guide to understand Pointers and Arrays in Golang.

Md. Faiyaj Zaman
3 min readMar 11, 2023

--

Welcome back to our Golang tutorial series. Today, we’ll be exploring pointers and arrays in Golang.

Hi there, fellow Golang enthusiasts. In this tutorial, we’ll be diving into pointers and arrays — two fundamental concepts that are essential to know if you want to write efficient and performant code in Golang.

Let’s start with pointers. In Golang, a pointer is a variable that stores the memory address of another variable. This enables us to manipulate that variable directly, rather than just a copy of it.

Here’s an example. Suppose we have a variable named “num” that stores the value 5. We can create a pointer to “num” using the “&” operator like this:

num := 5

ptr := &num

If we print out the value of “ptr”, we’ll see that it’s the memory address of “num”. We can also update the value of “num” directly through the pointer like this:

*ptr = 10

Pretty neat, right? Just be careful when working with pointers because they can easily lead to null pointer errors and memory leaks if not used correctly.

Now let’s move on to arrays. An array in Golang is a collection of elements of the same type that are stored contiguously in memory.

Here’s an example of how to declare an array in Golang:

var myArray [5]int

This creates an array called “myArray” that can hold 5 integers. We can access each element of the array using its index, which starts at 0.

We can also initialize the values of the array when we declare it like this:

myArray := [5]int{1, 2, 3, 4, 5}

But sometimes we need more flexibility with our data structures, and that’s where slices come in.

A slice is like a dynamic array in Golang that can grow or shrink as needed. It’s basically a view into an underlying array.

Here’s an example of how to create a slice in Golang:

mySlice := make([]int, 3, 5)

This creates a slice called “mySlice” with an initial length of 3 and a capacity of 5. We can add up to 2 more elements to the slice before it needs to be resized.

We can access each element of the slice using its index, just like with arrays. We can also append elements to the slice like this:

mySlice = append(mySlice, 4, 5)

And we can copy elements from one slice to another like this:

newSlice := make([]int, 2)

copy(newSlice, mySlice[:2])

And that’s a wrap on pointers and arrays in Golang! These concepts can be a bit tricky to grasp at first, but with a bit of practice, you’ll be able to write efficient and robust Golang code. Thanks for reading, and see you in the next tutorial.

If you have any questions or suggestions, feel free to leave them in the comments below. Until next time, happy coding!

--

--