Go pointer

Unlike pointers in C/C++, Go's pointers do not support arithmetic operations and offsetting, making them safe pointers.

Pointer Addresses and Pointer Types

Every variable at runtime has an address, which represents its location in memory. Go uses the & character placed before a variable to perform a "take the address" operation on that variable. Go's value types (int, float, bool, string, array, struct) all have corresponding pointer types, such as: *int, *int64, *string, etc.

var a int //declaring actual variables
var b *int //declare a pointer variable pointing to an integer

a = 10
b = &a //retrieve the memory address of the integer variable a and store it in a pointer variable b

fmt.Println("a:", a, ",ptr:", &a)  //a: 10 , ptr: 0xc0003d2f00
fmt.Printf("b:%p type:%T\n", b, b) //b:0xc0003d2f00 type:*int
fmt.Println("&b:", &b)             //&b: 0xc00008cc90

Illustration for b := &a

Go Pointer

Dereferencing Pointers

The address-of operator & and the dereference operator * are complementary: & fetches the address, while * fetches the value pointed to by the address.

  1. Performing the address-of (&) operation on a variable and assigning the address to a pointer variable.
  2. Performing the dereference (*) operation on a pointer variable to obtain the content pointed to by the pointer variable.

Nil Pointers

When a pointer is defined but not assigned to any variable, its value is nil. This indicates that the pointer does not point to any valid memory location.

Take a break

πŸ‘‰πŸ‘‰πŸ‘‰ 【BTTH Year EP108】Xiao Yan sent love message back to Medusa and prepared to rescue Xiao Yixian