In Go, a pointer is a variable that holds the memory address of another variable. Pointers are used to pass memory addresses between functions or to share data between multiple functions or goroutines.
To create a pointer in Go, you can use the &
operator followed by the variable you want the pointer to reference. Here is an example:
main.go423 chars18 lines
In this example, we declare a variable x
with an initial value of 10. We then declare a pointer ptr
of type *int
(pointer to an integer) and initialize it to the memory address of x
using the &
operator.
To access the value pointed to by the pointer, we use the *
operator. We can also modify the value of the original variable by indirectly referencing it through the pointer using the *
operator.
Note that Go has no pointer arithmetic like C or C++, which means you cannot use pointers to iterate through an array or perform other pointer arithmetic operations.
gistlibby LogSnag