assign a value to a pointer in go

In Go, you use the & operator to get the address of a variable and the * operator to declare a pointer variable and to dereference a pointer.

To assign a value to a pointer, you first need to declare the pointer variable and then assign its address to it. You can then use the pointer to indirectly access and modify the value of the variable it points to.

main.go
package main

import "fmt"

func main() {
    var num int = 42
    var ptr *int = &num
    fmt.Printf("Value of num: %d\n", num) // Output: Value of num: 42
    fmt.Printf("Value of ptr: %p\n", ptr) // Output: Value of ptr: <memory address of num>
    
    *ptr = 99 // assign 99 to the value pointed by ptr
    fmt.Printf("Value of num: %d\n", num) // Output: Value of num: 99
    fmt.Printf("Value of ptr: %p\n", ptr) // Output: Value of ptr: <memory address of num>
}
471 chars
15 lines

In the above code, we declare an integer variable num and a pointer variable ptr of type *int. We then assign the address of num to ptr using the & operator.

We can then indirectly modify the value of num by dereferencing the pointer using the * operator and assigning a new value to it. The value of num is then changed to 99.

Output:

main.go
Value of num: 42
Value of ptr: 0xc000016088
Value of num: 99
Value of ptr: 0xc000016088
88 chars
5 lines

gistlibby LogSnag