pass a pointer to a function in go

In Go, you can pass a pointer to a function by using the * operator to indicate that the argument is a pointer. Here is an example that demonstrates how to pass a pointer to a function:

main.go
package main

import "fmt"

type person struct {
    name string
    age  int
}

// The function below takes a pointer to a person struct as its argument
func changeName(p *person, name string) {
    p.name = name
}

func main() {
    p := person{name: "Bob", age: 25}
    fmt.Println("Before:", p)

    // Pass a pointer to the person struct to the changeName function
    changeName(&p, "Alice")

    fmt.Println("After:", p)
}
430 chars
24 lines

In the example above, the changeName function takes a pointer to a person struct as its first argument. The second argument is a new name value for the given person argument. To pass a pointer to the person struct to the changeName function, we use the & operator to get a reference to the person value.

The & operator returns the memory address of the person value, which is a pointer to its memory location. When we pass the pointer value to the changeName function, we are giving it direct access to the person value in memory, so any changes made to the person value inside the function will be reflected in the original person value outside the function.

This is one of the powerful features of Go – using pointers, we can pass large data structures around without copying them to new memory locations, which is especially useful when dealing with large sets of data.

gistlibby LogSnag