In Go, we can create a function that returns a pointer using the following syntax:
main.go278 chars11 lines
In the function createPointer()
, we first allocate memory for an integer using the new()
function. We then assign a value to the integer and return the pointer to the integer.
To call the createPointer()
function, we can simply assign its return value to a variable.
In the main()
function, we call createPointer()
and assign the returned pointer to the pointer
variable. We then dereference the pointer using the *
operator to print the value of the integer it points to.
It is important to note that we need to be careful when using pointers in Go, as there is no automatic memory management. We must manually allocate and deallocate memory for pointers to avoid memory leaks.
gistlibby LogSnag