Learning about the unsafe package can make it a little safer to use!
So in this video, we're going to talk about the unsafe package. The unsafe package in Go is a side door into Go's memory management. As you can tell by the name, using it is unsafe, and it bypasses many of Go's safety guarantees. This can give you powerful capabilities for performance optimizations, for manipulating memory, and for interfacing with hardware or system calls directly.
However, with great power comes responsibility, so you need to be careful not to misuse this as it can lead to data corruption and panics. Let's quickly run through the purpose and caveats that come with using the unsafe
package. First, let's look at unsafe.Pointer
.
We declare a float64 value, get a pointer to it, then use an unsafe pointer to reinterpret it as a uint64
. We print it again, modify the bits to be zero, and then print it a final time. You can see how the memory is reinterpreted, effectively turning 42.5 into a large integer, and then 0.0 when read back as a float. The Go compiler can't track these reinterpretations, so you're entering manual memory manipulation territory.
The unsafe
package is also helpful for discovering how fields are laid out in memory, using functions like Sizeof
, Alignof
, and Offsetof
. For example, you can run code that prints the size, alignment, and offset of struct fields, which is useful if you're curious about or need control over memory layout.
When might you use unsafe? If code is performance-critical and normal pointer conversions or data copying impose too much overhead, you might consider it. If you work with very low-level systems where I/O or hardware interaction is important, you might need it. Finally, if you're using a tool like cgo, it might rely on unsafe behind the scenes. However, if you're in doubt, you probably don't need it. Most Go developers go their entire careers without needing to touch the unsafe
package, but it's good to know it's there if you ever need to escape Go's memory management model and manage memory yourself.
Happy hacking! I hope you never need unsafe, but at least you're aware it exists should the need ever arise.