Functions that return pointers

As you learned in Chapter 4, The Uses of Composite Types, as illustrated in the pointerStruct.go program, it is considered a good practice to create new structure variables using a separate function and return a pointer to them from that function. So, the scenario of functions returning pointers is very common. Generally speaking, such a function simplifies the structure of a program and allows the developer to concentrate on more important things instead of copying the same Go code all the time. This section will use a much simpler example, as found in the Go code of returnPtr.go.

The first part of returnPtr.go contains the following Go code:

package main 
 
import ( 
   "fmt" 
) 
 
func returnPtr(x int) *int { 
   y := x * x 
   return &y 
} 

Apart from the expected preamble, this portion defines a new function that returns a pointer to an int variable. The only thing to remember is to use &y in the return statement in order to return the memory address of the y variable.

The second part of returnPtr.go is as follows:

func main() { 
   sq := returnPtr(10) 
   fmt.Println("sq:", *sq) 

As you already know, the * character dereferences a pointer variable, which means that it returns the actual value stored at the memory address instead of the memory address itself.

The last code segment from returnPtr.go is shown in the following Go code:

   fmt.Println("sq:", sq) 
} 

The preceding code will return the memory address of the sq variable, not the int value stored in it!

If you execute returnPtr.go, you will see the following output (the memory address will differ):

$ go run returnPtr.go
sq: 100
sq: 0xc420014088
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.51