Description
Proposal Details
Proposal: Add support for conditional compilation directives (similar to #define
/ #ifdef
) in Go
Introduction
Go currently does not support preprocessor directives like #define
or #ifdef
, which are widely used in C/C++ projects. This was an intentional design choice to keep the language clean and readable. However, for developers working on low-level, high-performance systems such as databases, file engines, or embedded runtimes, this limitation imposes significant friction.
Motivation
In C/C++, conditional compilation enables:
- Switching algorithms or implementations at build time.
- Stripping debug or logging code from production builds.
- Including architecture-specific optimizations.
- Maintaining a single source file with multiple code paths for different configurations.
In Go, we must simulate this with multiple files and //go:build
constraints, which fragments the logic and harms maintainability.
As a real-world example: I'm building a database engine in Go using a B+Tree structure with persistent storage, range scanning, and concurrency support. To extract maximum performance, I often need to:
- Enable or disable optimizations like async flush, page caching, or internal tracing;
- Use CPU-specific instructions or branching logic (e.g., arm64 vs amd64);
- Inject stress-testing behaviors or debug assertions conditionally.
Today, achieving that requires creating multiple build-tagged files with duplicated code, which scales poorly and adds maintenance overhead.
Proposal
Introduce a minimal, safe, and explicit form of conditional compilation to Go. Not necessarily with #define
or #ifdef
syntax, but something equivalent in functionality.
Example (hypothetical):
#if DEBUG
fmt.Println("debug info:", node)
#endif