Pointers
Pointers in Go are an essential feature that allows working directly with a program’s memory. A pointer stores the memory address of another variable. This can be useful for accessing and modifying the value stored at that specific memory address.
Pointer Declaration
In Go, a pointer is declared using the dereferencing operator (*
) before the data type to indicate that the variable is a pointer to that type of data. Then, to assign it the memory address of another variable, the &
operator is used:
var x int = 7var ptr *int = &xfmt.Println(ptr)
The output for the above code contains the memory address that the pointer is pointing to:
0xc000096068
In this example, ptr
is a pointer to an integer (*int
) that stores the memory address of the variable x
.
Accessing Values Through a Pointer
To access the value stored at the memory address pointed to by a pointer, the *
operator is used:
var x int = 7var ptr *int = &xfmt.Println(*ptr)
The above code will print the value stored at the memory address pointed to by ptr
:
7
Modifying Values Through a Pointer
Pointers allow developers to indirectly modify the value of a variable by accessing the memory address of that variable:
var x int = 7var ptr *int = &x*ptr = 10
This will change the value of the variable x
to 10, as ptr
points to the memory address of x
:
10
Checking for Null Pointers
In Go, pointers are automatically initialized with the null value (nil
). It’s important to check if a pointer is null before attempting to access the value it points to. Attempting to dereference a null pointer will result in a runtime panic, which may cause the program to stop abruptly:
var ptr *intfmt.Println(ptr)
The output for the above code is:
<nil>
Example
Here’s a comprehensive example that declares, initializes, accesses, and modifies values through pointers in Go:
package mainimport "fmt"func main() {x := 7var ptr *int = &xfmt.Println("Value of x:", x)fmt.Println("Memory address of x:", ptr)fmt.Println("Value pointed by ptr:", *ptr)*ptr = 10fmt.Println("New value of x:", x)}
The output for the above code is:
Value of x: 7Memory address of x: 0xc00000a0f8Value pointed by ptr: 7New value of x: 10
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Go
Learn how to use Go (Golang), an open-source programming language supported by Google!Beginner Friendly6 hours