Logo

Developer learning path

Go

Pointers and Variables in Go

Pointers and Variables

11

#description

In Go programming language, a pointer is a variable that stores the memory address of another variable. Variables are declared with a specific type, and pointers also need to point to a specific type.

For example, to declare a pointer to an integer variable in Go, we would use the following syntax:

                    
var ptr *int
                  

Here, ptr is a variable of type pointer to an integer (*int). We can initialize this pointer with the memory address of an integer variable using the & symbol, which returns a pointer to the operand.

For example:

                    
num := 42
ptr = &num
                  

Here, we are initializing ptr with the memory address of the num integer variable, using the &num syntax.

Once we have a pointer to a variable, we can use the * operator to access or modify the value stored at that memory address.

For example:

                    
*ptr = 24
                  

Here, we are using the * operator to modify the value stored at the memory address pointed to by ptr, which is the num variable we originally initialized it with. This statement changes the value of num to 24.

Pointers are often used for passing variables as parameters to functions, where the function can modify the original variable by accessing it through the pointer. Additionally, pointers can be used to allocate and deallocate memory dynamically, which can be useful for managing large data structures.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.