Passing Pointers to a Function in Go

Passing pointers to functions in Go allows you to work directly with the original data, enabling you to modify values or avoid unnecessary copying of large data structures. Here’s a step-by-step breakdown of how to pass pointers to functions in Go:

Declare a Struct (Optional): If you’re working with more complex data, you might want to define a struct to hold your data. For this example, let’s define a simple struct named Person:

type Person struct {
    Name string
    Age  int
}

Define a Function: Create a function that accepts a pointer as an argument. In this example, we’ll create a function that modifies the age of a person:

func modifyAge(p *Person, newAge int) {
    p.Age = newAge
}

Create an Instance of the Struct: Create an instance of the Person struct and initialize its values:

func main() {
    person := Person{Name: "Alice", Age: 25}
    fmt.Println("Original Age:", person.Age) // Output: Original Age: 25
}

Pass the Pointer to the Function: When calling the function, pass the address of the Person instance to the function using the & operator:

modifyAge(&person, 30)
fmt.Println("Modified Age:", person.Age) // Output: Modified Age: 30

By passing &person, you’re passing a pointer to the person struct, allowing the function to modify the original data.

Putting it all together:

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func modifyAge(p *Person, newAge int) {
    p.Age = newAge
}

func main() {
    person := Person{Name: "Alice", Age: 25}
    fmt.Println("Original Age:", person.Age) // Output: Original Age: 25

    modifyAge(&person, 30)
    fmt.Println("Modified Age:", person.Age) // Output: Modified Age: 30
}

In this example, the modifyAge function accepts a pointer to a Person instance, modifies its age, and the change is reflected in the original person instance. This showcases how passing pointers to functions can be used to modify data directly and avoid unnecessary data copying.