The unsafe package
- Go course
- Advanced
- Lesson 7/68
- 4 min
Learn the risks and usage of the unsafe package.
The unsafe package
The unsafe package lets you deliberately step around Go's type safety: convert pointers between types and learn a type's size and alignment in memory.
var n int64
fmt.Println(unsafe.Sizeof(n)) // 8Its name is a warning: code using it may not be portable across Go versions and architectures.
When is it used?
Real use cases are narrow: zero-copy conversions (e.g. []byte ↔ string), system calls, sharing data with C, and optimizing very hot code paths. In the standard library, runtime, reflect and syscall use unsafe; application code almost never needs it.
Practice Print the sizes
Use unsafe.Sizeof to print the sizes of an int8, an int64 and a float32 with one fmt.Println.
Starter code
package main
import (
"fmt"
"unsafe"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"unsafe"
)
func main() {
var a int8
var b int64
var c float32
fmt.Println(unsafe.Sizeof(a), unsafe.Sizeof(b), unsafe.Sizeof(c))
}Expected output
1 8 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is true for code that uses unsafe?
- It is always safer
- It turns off the garbage collector
- It only runs on Windows
- It may fall outside the Go compatibility promise Correct answer
Explanation: The Go 1 compatibility promise does not cover programs that use unsafe; they may break when the compiler or runtime changes.
2 Learn the size
var x int32
fmt.Println(unsafe.____(x)) // 4
var x int32
fmt.Println(unsafe.Sizeof(x)) // 4
Explanation: unsafe.Sizeof returns a value's size in bytes; 4 for int32.
3 unsafe tools
| Term | Meaning |
|---|---|
unsafe.Pointer |
Converts to any pointer |
unsafe.Sizeof |
Size in bytes |
unsafe.Alignof |
Alignment |
unsafe.Offsetof |
Field offset |