retrieve a value from a pointer in go

To retrieve a value from a pointer in Go, you need to first allocate memory for the variable using the new keyword or by using a specific pointer syntax. Once the memory is allocated, you can store a value in the memory location pointed to by the pointer. To retrieve the value, you simply need to dereference the pointer.

Here is an example:

main.go
package main

import "fmt"

func main() {
   var ptr *int
   var val int = 5

   ptr = &val

   // Dereferencing the pointer to retrieve the value
   fmt.Println("Value of val :", val)
   fmt.Println("Value of *ptr :", *ptr)
}
227 chars
15 lines

In this example, we first declare a pointer variable ptr of type *int and a value variable val of type int. We then assign the address of val to ptr using the & operator.

To retrieve the value stored at the memory location pointed to by ptr, we use the * operator to dereference the pointer. In the example, *ptr would output the value 5, which is the value stored in the variable val.

gistlibby LogSnag