Variables and Constants
Zig provides two ways to declare identifiers:var for variables and const for constants.
Constants
Constants are declared withconst and cannot be changed after initialization:
Variables
Variables are declared withvar and can be modified:
Variables declared with
var must have their types explicitly specified or inferred from initialization.Container-Level Variables
Variables and constants can be declared at the container level (file scope):Container-level variables are evaluated in dependency order, not declaration order.
Assignment
Direct Assignment
Assignment in Zig is straightforward with the= operator:
Undefined Values
You can useundefined to leave a variable uninitialized:
Comments
Zig supports two types of comments:Line Comments
Line comments start with// and continue to the end of the line:
Doc Comments
Doc comments are used for documentation generation and start with///:
Compile-Time vs Runtime
Zig distinguishes between compile-time and runtime values:Identifiers
- Standard Identifiers
- @-prefixed Identifiers
Standard identifiers must start with a letter or underscore and contain only alphanumeric characters and underscores:
Best Practices
- Prefer
constovervarwhen the value doesn’t need to change - Use descriptive names for identifiers
- Initialize variables at declaration when possible
- Use
undefinedsparingly and only when necessary for performance