Skip to Content
Learning Go
book

Learning Go

by Jon Bodner
March 2021
Beginner
375 pages
8h 59m
English
O'Reilly Media, Inc.
Content preview from Learning Go

Chapter 14. Here There 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 our previous sections, we 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 of 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, we’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 only be provided 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Go, 2nd Edition

Learning Go, 2nd Edition

Jon Bodner

Publisher Resources

ISBN: 9781492077206Errata PageSupplemental Content