create a function that accepts a pointer in go

To create a function in Go that accepts a pointer, you need to define the parameter type as a pointer. Here's an example of a function that takes a pointer to an integer:

main.go
func addOne(numPtr *int) {
    *numPtr += 1
}
46 chars
4 lines

In this function, numPtr is a pointer to an integer (*int), which is passed to the function. The * symbol before numPtr is used to dereference the pointer and access the integer value it points to.

To call this function, you need to pass the address of an integer, using the & operator:

main.go
num := 1
addOne(&num)
fmt.Println(num) // Output: 2
52 chars
4 lines

Here, num is an integer variable with the value 1. To pass its address to the addOne function, you use the & operator (&num) to get a pointer to the variable. When the addOne function modifies the value of *numPtr, it modifies the original num variable as well.

related categories

gistlibby LogSnag