We use address and dereference operators to work with memory locations directly. This helps us change values in one place and see the change everywhere that value is used.
0
0
Address and dereference operators in Go
Introduction
When you want to change a variable's value inside a function and see the change outside.
When you want to share large data without copying it, to save memory.
When you want to link data structures like lists or trees by pointing to other elements.
When you want to check or modify the actual memory location of a variable.
Syntax
Go
var p *int = &x // & gets the address of x var y int = *p // * gets the value stored at address p
The & operator gives you the memory address of a variable.
The * operator lets you access or change the value at that memory address.
Examples
Here,
p stores the address of x. Printing p shows where x lives in memory.Go
x := 10 p := &x fmt.Println(p) // prints memory address of x
The
*p gets the value stored at the address p points to, which is x's value.Go
x := 10 p := &x fmt.Println(*p) // prints 10
Changing
*p changes x because p points to x.Go
x := 10 p := &x *p = 20 fmt.Println(x) // prints 20
Sample Program
This program shows how to get the address of a variable x using &, read its value using *, and change it through the pointer.
Go
package main import "fmt" func main() { x := 5 p := &x fmt.Println("Address of x:", p) fmt.Println("Value of x:", *p) *p = 10 fmt.Println("New value of x after change through pointer:", x) }
OutputSuccess
Important Notes
Pointer variables store memory addresses, not the actual values.
Dereferencing a pointer (*p) lets you read or change the value at that address.
Always initialize pointers before dereferencing to avoid errors.
Summary
The & operator gets the address of a variable.
The * operator accesses or changes the value at a given address.
Using pointers helps share and modify data efficiently.