Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Garbage Collection in Go (Golang). If you're new to programming, don't worry! We'll cover everything from the ground up.
In programming, memory management is crucial. Garbage Collection is a process that automatically reclaims memory occupied by objects that are no longer in use, thus preventing memory leaks. Let's see why it's essential and how it works in Go.
Go uses a concurrent garbage collector to balance efficiency and responsiveness.
Let's create a simple Go program that demonstrates garbage collection.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("Starting the program.")
// Create a large slice to force garbage collection.
data := make([]int, 1000000)
// Run the garbage collector.
runtime.GC()
fmt.Println("Garbage collected.")
// Measure the number of bytes in use.
mem := runtime.MemStats{}
runtime.ReadMemStats(&mem)
fmt.Printf("Alloc: %v\n", mem.Alloc)
fmt.Printf("TotalAlloc: %v\n", mem.TotalAlloc)
fmt.Printf("Sys: %v\n", mem.Sys)
fmt.Printf("NumGC: %v\n", mem.NumGC)
}When you run this program, it creates a large slice of integers, triggers garbage collection, and then measures the memory statistics.
What does Go's garbage collector do?
That's it for today! In the next lesson, we'll dive deeper into Go's concurrent garbage collector and see how it balances efficiency and responsiveness.
Stay tuned and happy coding! 🎉💻🎯