A pointer in Go is a variable that stores the memory address of another variable. Pointers are useful to modify the value of a variable indirectly or share large data structures efficiently without copying the whole structure. The Go pointer type is denoted with a ‘*‘ followed by the type of the variable it points to.
Here’s a brief summary of pointers in Go, followed by examples and additional details:
1. Declare a pointer: ‘var pointerVar *Type‘
2. Get the address of a variable: ‘&variable‘
3. Access the value of a variable via a pointer: ‘*pointerVar‘
4. Pass-by-reference: Modify the value of a variable indirectly.
Now, let’s see some examples and additional explanations:
1. Declare a pointer:
var integerVar int = 10
var integerPointer *int // declaring an integer pointer
2. Get the address of a variable and store it in the pointer:
integerPointer = &integerVar
3. Access the value of a variable via a pointer:
value := *integerPointer
In this example, the value of ‘value‘ variable will be the value of the ‘integerVar‘, which is 10.
4. Modify a variable indirectly via a pointer:
*integerPointer = 20
This will change the value of ‘integerVar‘ to 20.
When it comes to functions, pointers can be used to create pass-by-reference behavior. In Go, function arguments are passed by value, meaning the function receives a copy of the original variable. With pointers, you can modify the original variable within the function.
Here’s a simple example demonstrating the use of pointers with functions:
package main
import "fmt"
func addOne(num *int) {
*num = *num + 1 // Modify the original value pointed by the pointer.
}
func main() {
number := 1
fmt.Println("Before:", number) // Output: Before: 1
addOne(&number)
fmt.Println("After:", number) // Output: After: 2
}
In this example, we’re using a pointer as an argument for the ‘addOne‘ function, effectively allowing us to modify the original ‘number‘ variable.
In conclusion, pointers in Go can be very useful to modify variable values indirectly or share large data structures between functions in an efficient manner by avoiding excessive copying. Always be cautious when using pointers, as incorrect handling might lead to unexpected behavior or vulnerabilities like null pointer dereferences.