Chapter 16. Here Be Dragons: Reflect, Unsafe, and Cgo
The edges of the known world are scary. Ancient maps would fill in the unexplored areas with pictures of dragons and lions. In the previous sections, I have emphasized that Go is a safe language, with typed variables to make clear what sort of data you are using and garbage collection to manage memory. Even the pointers are tame; you can’t abuse them in the way that C and C++ do.
All those things are true, and for the vast majority of the Go code that you’ll write, you can be assured that the Go runtime will protect you. But there are escape hatches. Sometimes your Go programs need to venture out into less defined areas. In this chapter, you’re going to look at how to handle situations that can’t be solved with normal Go code. For example, when the type of the data can’t be determined at compile time, you can use the reflection support in the reflect
package to interact with and even construct data. When you need to take advantage of the memory layout of data types in Go, you can use the unsafe
package. And if there is functionality that can be provided only by libraries written in C, you can call into C code with cgo
.
You might be wondering why these advanced concepts appear in a book targeted at those new to Go. There are two reasons. First, developers searching for a solution to a problem sometimes discover (and copy and paste) techniques they don’t fully understand. It’s best to know a bit about advanced techniques that ...
Get Learning Go, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.