View : 0

12/04/2026 18:15pm

EP.6 Go and Pointers - Mastering Memory Management!

EP.6 Go and Pointers - Mastering Memory Management!

#Go Programming

#nil Pointer

#Memory Management

#Pointers

#Go

Go and Pointers - Mastering Memory Management!

Have you ever wondered how programs manage data in memory? Pointers in Go allow you to access and modify values directly through memory addresses.

What is a Pointer?

In Go, a Pointer is a variable that holds the memory address of a value or another variable. It enables us to access and modify values directly through memory.

Example:

package main

import "fmt"

func main() {
    x := 10
    ptr := &x // เก็บที่อยู่ของตัวแปร x
    fmt.Println("Address of x:", ptr) // แสดงที่อยู่หน่วยความจำ
    fmt.Println("Value of x:", *ptr)  // ดึงค่า x ผ่าน pointer
}

 

Using Pointers in Functions

Functions can receive values by reference through Pointers, allowing you to directly modify the original variable's value:

func changeValue(num *int) {
    *num = 100
}

func main() {
    x := 10
    changeValue(&x)
    fmt.Println("Updated value of x:", x) // Output: 100
}

 

Memory Management in Go

Go has a Garbage Collector that automatically manages memory. However, understanding how to use Pointers will help you write efficient programs and avoid unnecessary memory usage.

Nil Pointer and Pointer Checking

A Pointer that does not point to any variable will have a value of nil:

var ptr *int
if ptr == nil {
    fmt.Println("Pointer is nil")
}

 

You can try creating a function that uses a Pointer to swap the values of two variables.

Example:

func swap(a, b *int) {
    temp := *a
    *a = *b
    *b = temp
}

func main() {
    x, y := 1, 2
    swap(&x, &y)
    fmt.Println("x:", x, "y:", y) // Output: x: 2 y: 1
}