Functions with pointer parameters

Function can take pointer parameters provided that their signature allows it. The Go code of ptrFun.go will illustrate the use of pointers as function parameters.

The first part of ptrFun.go follows next:

package main 
 
import ( 
   "fmt" 
) 
 
func getPtr(v *float64) float64 { 
   return *v * *v 
} 

So, the getPtr() function accepts a pointer parameter that points to a float64 value.

The second part of the program is shown in the following Go code:

func main() { 
   x := 12.2 
   fmt.Println(getPtr(&x)) 
   x = 12 
   fmt.Println(getPtr(&x)) 
} 

The tricky part here is that you need to pass the address of the variable to the getPtr() function because it requires a pointer parameter, which can be done by putting an ampersand in front of a variable (&x).

Executing ptrFun.go will generate the following kind of output:

$ go run ptrFun.go
148.83999999999997
144

If you try to pass a plain value such as 12.12 to getPtr() and call it like getPtr(12.12), the compilation of the program will fail, as shown in the following the next error message:

$ go run ptrFun.go
# command-line-arguments
./ptrFun.go:15:21: cannot use 12.12 (type float64) as type *float64 in argument to getPtr
..................Content has been hidden....................

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