The unsafe Package
Go is a statically typed language, and it has its own runtime that does memory allocation and garbage collection. So, unlike C, all the work related to memory management is taken care of by the runtime. Unless you have some special requirements, you would never have to deal with memory directly in your code. When there is a requirement, though, the unsafe
package in the standard library gives you features to let you peek into the memory of an object.
As the name suggests, it is normally not considered safe to use this package in your code. Another thing to note is that the unsafe
package does not come with Go 1 compatibility guidelines, which means that functionalities could stop working in future versions of Go.
The simplest example you can find of using the unsafe
package can be found in the math
package:
func Float32bits(f float32) uint32 { Â Â return *(*uint32)(unsafe.Pointer(&f)) }
This takes a float32
as input and returns uint32
. The...