0
0
Goprogramming~5 mins

Pointer declaration in Go

Choose your learning style9 modes available
Introduction

Pointers let you store the address of a variable. This helps you change the original value from different places in your program.

When you want to change a variable inside a function and keep the change outside.
When you want to save memory by not copying large data, just passing its address.
When you want to share data between parts of your program safely.
When you want to work with data structures like linked lists or trees.
Syntax
Go
var p *int

// or

var p *Type

The asterisk (*) before the type means this variable holds a pointer to that type.

Pointer variables store memory addresses, not the actual value.

Examples
Declares a pointer to an integer.
Go
var p *int
Declares a pointer to a string.
Go
var name *string
Declares a pointer to a float64 value.
Go
var p *float64
Sample Program

This program shows how to declare a pointer, assign it the address of a variable, and change the variable's value through the pointer.

Go
package main

import "fmt"

func main() {
    var x int = 10
    var p *int = &x  // p holds the address of x

    fmt.Println("Value of x:", x)
    fmt.Println("Address of x stored in p:", p)
    fmt.Println("Value pointed to by p:", *p)

    *p = 20  // change value at address p points to
    fmt.Println("New value of x after change through p:", x)
}
OutputSuccess
Important Notes

Use the ampersand (&) to get the address of a variable.

Use the asterisk (*) to get or set the value at the pointer's address.

Pointer addresses will look different each time you run the program.

Summary

Pointers store addresses of variables, not the actual values.

Use & to get a variable's address and * to access or change the value at that address.

Pointers help you work with data efficiently and allow functions to modify variables outside their scope.