Learn about pointers and memory addresses in Go. Some things are more easily done with pointers, others without. Eitherway pointers are fun to work with!
Not all programming languages support pointers, typically they are found in low level languages like C or C++. Go also supports them.
Learn How To Code: Google’s Go (golang) Programming Language
Every variable is is stored in the memory and has a unique address. This can be accessed with the ampersand (&) operator.
If you run the code with the command
go run program.go
You will see the program tells you the memory address and the contents in that memory address.
Address of variable x: c4200160d8
Value of variable x: 5
The memory address will be different on your computer, value the same.
A pointer is a variable whose address is the direct memory address of another variable.
The asterisk * is used to declare a pointer.
The form is:
var var_name *var-type
You have to write the variable type,
/* pointer to an integer */
So lets see that in an example
This will output something like:
Memory address of variable x: c4200160d8
- Where are variables stored in the computer?
- What is a pointer?
- How can you declare a pointer?