Brussels / 2 & 3 February 2019


When and How to use CGo

Or, Foreign Functions for Fun and Profit

Go is, for all its C-esque syntax, is a relatively high-level language. There’s garbage collection, a type hierarchy, and even advanced concurrency primitives. Sometimes, though, you need access to lower-level control. Whether for performance, interoperability, or just for fun, the Cgo API is here to help! I will explain what it is, how to use it, and perhaps most importantly, when to avoid it.

A lot of Go programmers only experience with Cgo is when compilation fails with some obscure error. There’s a lot more to learn than that, and a lot of opportunities! I’ve personally used Cgo for writing Postgres foreign wrappers, and as a consumer when compiling Kubernetes.

Using Cgo can be a fun, rewarding experience. There are a lot of existing projects and libraries written in C, and calling them means not needing to reinvent the wheel. On the same face, if you have an existing project with a C API, calling Go can get you some of the higher-level Go niceness on top of the jagged C edges.

Some things I intend to touch on: * Calling Go from C * Calling C from Go * Memory management with Go objects in C * Using C libraries from Go * Real-world Cgo examples * The pitfalls Go and dynamic linking * Debugging failures


Photo of Liz Frost Liz Frost