This tutorial aims to provide an easy-to-understand guide on how to use pointers in Go programming language. Pointers can be intimidating for new programmers, but with a clear understanding of their concept, they can become a powerful tool in your coding arsenal.
By the end of this tutorial, you will understand what pointers are, how to declare and use them, and why they are useful in Go.
Prerequisites: Basic knowledge of Go programming is required.
2. Step-by-Step Guide
A pointer in Go is a variable that stores the memory address of another variable. The variable that stores the address is the pointer, and the variable whose address is being stored is the pointee.
Pointers are declared using the * operator before the type of the stored value. The & operator is used to get the address of a variable.
Here is how you can declare a pointer: var p *int, where p is a pointer to an int.
Here is how you can get the address of a variable: p = &i, where i is an int variable and p is the address of i.
3. Code Examples
Let's see an example:
package main
import "fmt"
func main() {
var i int = 10 // declare int variable
fmt.Printf("Value of i: %d\n", i)
var p *int // declare pointer to int
p = &i // assign address of i to p
fmt.Printf("Address of i: %d\n", p)
}
In the above code:
We first declare an int variable i and assign a value of 10 to it.
Then we declare a pointer p to an int.
We assign the address of i to p using the & operator.
The output will be the value of i and the memory address of i.
4. Summary
Pointers in Go are variables that store the address of another variable.
They are declared using the * operator, and the & operator is used to store the address of another variable in a pointer.
Pointers are useful for sharing large data structures without copying the data, and for changing multiple variables in a function.
5. Practice Exercises
Declare two int variables, assign values to them, declare a pointer for each, and print their addresses.
Write a function that takes a pointer to an int as a parameter, changes the value of this int, and prints the new value in the main function.
Write a function that takes a pointer to an array as a parameter, changes an element in this array, and prints the new array in the main function.
Solutions:
package main
import "fmt"
func main() {
var i1, i2 int = 5, 10
var p1, p2 *int
p1 = &i1
p2 = &i2
fmt.Printf("Address of i1: %d, Address of i2: %d\n", p1, p2)
}
package main
import "fmt"
func changeValue(p *int) {
*p = 20
}
func main() {
var i int = 10
fmt.Printf("Before: %d\n", i)
changeValue(&i)
fmt.Printf("After: %d\n", i)
}