create a function that returns a pointer in go

In Go, we can create a function that returns a pointer using the following syntax:

main.go
func createPointer() *int {
    pointer := new(int) // allocating memory for an int
    *pointer = 10       // assigning a value to the int
    return pointer      // returning the pointer
}

func main() {
    pointer := createPointer()
    fmt.Println(*pointer) // prints 10
}
278 chars
11 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