Go Example: Pointers

1. Introduction

Pointers are a fundamental concept in many programming languages, including Go. They allow you to reference and manipulate the memory address of a variable. This blog post will explain how to use pointers in Go with clear examples.

Definition

A pointer in Go is a variable that stores the memory address of another variable. Pointers are used to access and change the values of variables indirectly.

2. Program Steps

1. Declare an integer variable and a pointer to an integer.

2. Assign the memory address of the integer variable to the pointer.

3. Change the value of the integer variable using the pointer.

4. Pass a pointer to a function to allow the function to modify the value of the variable.

3. Code Program

package main

import "fmt"

// zeroval doesn't change the i in main, but zeroPtr does because it has a reference to the memory address for that variable.
func zeroval(ival int) {
	ival = 0
}

func zeroPtr(iptr *int) {
	*iptr = 0
}

func main() {
	i := 1
	fmt.Println("initial:", i)

	// Step 1 & 2: Assign the memory address of i to a pointer
	ptr := &i
	fmt.Println("pointer:", ptr)
	fmt.Println("pointer value:", *ptr)

	// Step 3: Change i using the pointer
	*ptr = 3
	fmt.Println("ptr:", *ptr)
	fmt.Println("i:", i)

	// Step 4: Pass the pointer to a function
	zeroval(i)
	fmt.Println("zeroval:", i)
	zeroPtr(&i)
	fmt.Println("zeroPtr:", i)

	// Print the pointer's memory address
	fmt.Println("pointer:", ptr)
}

Output:

initial: 1
pointer: 0xc0000120b8
pointer value: 1
ptr: 3
i: 3
zeroval: 3
zeroPtr: 0
pointer: 0xc0000120b8

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for formatted output.

3. The integer i is initialized to 1.

4. ptr is declared as a pointer to an int and is assigned the memory address of i using the & operator.

5. *ptr dereferences the pointer, allowing access to the value at the memory address ptr is pointing to.

6. zeroval is a function that takes an int parameter and sets it to 0. It does not affect i because it's working with a copy.

7. zeroPtr, on the other hand, takes a pointer to an int, dereferences it, and sets the underlying value to 0. This affects i because it changes the value at the memory address that ptr points to.

8. The output shows the initial value of i, how its value is accessed and changed via a pointer, and the effects of passing i to zeroval and &i to zeroPtr.


Comments