retrieve a value from a pointer to an int in go

To retrieve a value from a pointer to an int in Go, you need to use the dereferencing operator *.

Here's an example:

main.go
package main

import (
	"fmt"
)

func main() {
	var ptrToInt *int
	var intValue int = 42

	ptrToInt = &intValue

	fmt.Println("Pointer to int:", ptrToInt)
	fmt.Println("Dereferenced pointer to int:", *ptrToInt)
}
213 chars
16 lines

In this example, we initialize a pointer to an int ptrToInt and an int value intValue. We then assign the address of intValue to ptrToInt using the address-of operator &.

To retrieve the value stored in ptrToInt, we use the dereferencing operator * in the fmt.Println statement which produces the following output:

main.go
Pointer to int: 0x40c128
Dereferenced pointer to int: 42
57 chars
3 lines

So the output shows the actual memory address of the intValue variable and the value stored in it, respectively.

related categories

gistlibby LogSnag