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.go430 chars24 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