How does CGo work in Go?

Answer

CGo enables Go programs to call C code (and vice versa) by embedding C declarations in a special comment block immediately followed by import "C". Go types and C types are bridged via the pseudo-package C: C.int, C.CString, C.free. The Go compiler generates the necessary glue code and links against the C library. However, CGo has significant costs: it disables cross-compilation (the target machine needs a C toolchain), calls across the Go-C boundary are ~4x slower than pure Go calls (context switching between the Go scheduler and OS threads), and the binary becomes larger and harder to deploy. Prefer pure Go alternatives and use CGo only when wrapping an existing C library with no Go equivalent.