[Golang 01/30] Go pointer and variable

vikbert

Xun Zhou

Posted on May 24, 2023

[Golang 01/30] Go pointer and variable

Pointer in Golang is a variable which is used to stores the memory address of another variable. The memory address is always found in hexadecimal format, i.e. 0xFFAAF etc.

Most important operators we will used in pointer are:

  • operator *

    • declare pointer variable
    • access the value stored in that address
  • operator &

    • return the address of a variable
package main

import (
    "fmt"
)

func main() {

    // declare a variable
    var myVar int = 5

    // declare a pointer variable for type "int"
    var pointerVar *int

    // assign the address to that pointer variable
    pointerVar = &myVar

    fmt.Printf("\nAn integer %d is assigned to 'myVar', its location in memory: %p", myVar, &myVar)
    fmt.Printf("\nThe Value at memory location %p is %d", pointerVar, *pointerVar)

    // overwrite the content at the address
    *pointerVar = 100
    fmt.Printf("\nThe Value at memory location %p is changed to %d", pointerVar, *pointerVar)
    fmt.Printf("\nThe Value of 'myVar' with same address is changed to %d, too.", myVar)
}
Enter fullscreen mode Exit fullscreen mode

It prints the following content:

An integer 5 is assigned to 'myVar', its location in memory: 0xc0000b8000
The Value at memory location 0xc0000b8000 is 5
The Value at memory location 0xc00001c030 is changed to 100
The Value of 'myVar' with same address is changed to 100, too.
Enter fullscreen mode Exit fullscreen mode

Image description

Summary

Here & is used to get the address of the variable myVar, so &myVar and pointerVar has the same value 0xc0000b8000.
* symbol is used to read the value at memory address 0xc0000b8000, so *pointerVar shows the same content 5 as myVar.

💖 💪 🙅 🚩
vikbert
Xun Zhou

Posted on May 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related