We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

When and How to use CGo

Formal Metadata

Title
When and How to use CGo
Subtitle
Or, Foreign Functions for Fun and Profit
Title of Series
Number of Parts
561
Author
License
CC Attribution 2.0 Belgium:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
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