Member-only story
Go: What is the Unsafe Package?
ℹ️ This article is based on Go 1.12.
The name of the package could let us know that we should not use it. To understand the reasons that it could be unsafe to use this package, let’s first refer to the documentation:
Package unsafe contains operations that step around the type safety of Go programs.
Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.
The name is therefore used as opposition of the safeness that provide the types with Go. Let’s dive now into those two points mentioned by the documentation.
Type safety
In Go, each variable has a type that can be converted to another type before being assigned to another variable. During this conversion, Go performs a transformation of this data in order to fit with the requested type. Here is an example:
var i int8 = -1 // -1 binary representation: 11111111
var j = int16(i) // -1 binary representation: 11111111 11111111
println(i, j) // -1 -1
The unsafe
package will give us a direct access to the memory of this variable with the raw binary value stored at this address. It is up to us to use it as we want when bypassing the type constraint:
var k uint8 = *(*uint8)(unsafe.Pointer(&i))
println(k) // 255…