What Is the unsafe Package in Go

The unsafe package in Go allows direct memory access and type manipulation, bypassing standard type safety for performance or C interoperability.

The unsafe package in Go provides low-level operations that bypass the language's type safety and garbage collection rules, allowing direct memory manipulation. It is primarily used to implement high-performance libraries, interface with C code via cgo, or create custom memory allocators like arenas.

package main

import (
	"unsafe"
)

func main() {
	var x int
	var y float64

	// Get the address of x
	p := unsafe.Pointer(&x)

	// Cast the pointer to a float64 pointer
	py := (*float64)(p)

	// Write a float value to the memory location of x
	*py = 3.14

	// Read the value back as an int (bit pattern interpretation)
	println(x)
}

This code demonstrates casting a pointer from one type to another and writing data directly to memory, which is undefined behavior in safe Go but essential for systems programming.