Today we’re venturing into dangerous territory… the unsafe
package!
You can go years working in Go (as I have) without ever using unsafe
, or just barely bumping into it. On the other hand, somd developers spend significant time using unsafe
, to get the utmost performance out of their code, by working around the type system.
Using unsafe
can be powerful and beneficial. But… do it with the understanding that you’re giving up the benefits of memory and type safety, and cross-platform compatibility.
System considerations
Package unsafe
The built-in package
unsafe
, known to the compiler and accessible through the import path"unsafe"
, provides facilities for low-level programming including operations that violate the type system. A package usingunsafe
must be vetted manually for type safety and may not be portable. The package provides the following interface:package unsafe type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type type Pointer *ArbitraryType func Alignof(variable ArbitraryType) uintptr func Offsetof(selector ArbitraryType) uintptr func Sizeof(variable ArbitraryType) uintptr type IntegerType int // shorthand for an integer type; it is not a real type func Add(ptr Pointer, len IntegerType) Pointer func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType func SliceData(slice []ArbitraryType) *ArbitraryType func String(ptr *byte, len IntegerType) string func StringData(str string) *byte
A
Pointer
is a pointer type but aPointer
value may not be dereferenced. Any pointer or value of core typeuintptr
can be converted to a type of core typePointer
and vice versa. The effect of converting betweenPointer
anduintptr
is implementation-defined.var f float64 bits = *(*uint64)(unsafe.Pointer(&f)) type ptr unsafe.Pointer bits = *(*uint64)(ptr(&f)) func f[P ~*B, B any](p P) uintptr { return uintptr(unsafe.Pointer(p)) } var p ptr = nil
If you’re the kind of person, (perhaps due to childhood trauma?) who enjoys pointer arithmetic, this is the way to do it in Go!
I won’t be going into many details with the unsafe
package, for two reasons:
- I’m not very experienced with it (and I like it that way)
- Using it properly is a pretty advanced topic, and would not generally appeal to my readers.
I will talk about some of the more generally useful bits of unsafe
in the coming days, though. So stay tuned.
Meanwhile… stay safe! 😉
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)