Lesson 10Working with Pointers

Go supports pointers. A pointer is a variable that stores the memory address of another variable where the data is stored, rather than storing a value itself. In this lesson, we will look at the use of pointers.

CREATING A POINTER

All variables in Go other than maps and slices are value types. What that means is that if you have a variable that you are passing to a function and you want to make changes to the variable outside of the function, you can't change the variable directly. A copy gets passed in whenever you send it to a function.

If you want to modify the variable, the general approach is to use a pointer to the memory address instead of trying to affect the variable itself. In other words, you can pass in a pointer to the address of the variable, rather than passing a copy of the value itself. When you pass in a pointer, both the original value and the value used in the function are pointing to the same part of memory. Because they're pointing to the same spot in memory, when you change one value, both variables are changed.

Pointers are also used to pass in larger variables. If you have a large struct, then your ...

Get Job Ready Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.