Zig Variables and Constants
In the Zig language, a variable is a container for storing data.
In Zig, defining and using variables is very intuitive and powerful.
This article will detail how to define and use variables in Zig, including constants, variables, type inference, scope, and other aspects.
In Zig, constants are defined using the const keyword, while variables are defined using the var keyword.
Variables
In Zig, variables are defined using the var keyword.
A variable must explicitly specify its type at definition, or let the compiler infer the type through an initial value.
Variable Declaration
In Zig, declaring a variable requires specifying its type; the variable declaration syntax is as follows:
var variable_name: type = value;
variable_name is the variable name,type is the type,value is the variable value.
For example:
var x: i32 = 42; // 定义一个 i32 类型的变量 x,初始值为 42
var y = 10; // 编译器推断 y 的类型为 comptime_int
The value of a variable can be modified during program execution:
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
var b
:
i32
=
20
;
// Define an integer variable b with initial value 20
b
=
30
;
// Modify the value of variable b
std.
debug
.
(
"b: {}\n"
, .
{
b
}
)
;
}
Variable Characteristics
1. The Type Must Be Explicit:
-
Zig is a strongly typed language; the variable's type must be explicitly specified at definition, or inferred through an initial value.
-
If there is no initial value, the type must be explicitly specified.
Example
var x
:
i32
=
10
;
// Explicitly specify the type
var y
=
20
;
// The compiler infers the type as comptime_int
2. Mutability:
-
Use
varVariables defined with var are mutable and their values can be modified in subsequent code.
Example
var x
:
i32
=
10
;
x
=
20
;
// Modify the value of x
3. Scope:
-
The scope of a variable is block scope, meaning it is valid within the code block where it is defined.
Example
{
var x
:
i32
=
10
;
std.
debug
.
(
"x = {}\n"
, .
{
x
}
)
;
// Output: x = 10
}
// Here x is out of scope and cannot be accessed
4. Uninitialized Variables:
-
Zig does not allow the use of uninitialized variables. If a variable is not initialized, the compiler will report an error.
Example
var x
:
i32
;
// Error: variable x is not initialized
x
=
10
;
// Must be initialized first
Variable Types
Zig supports multiple data types, including but not limited to:
- Basic types: integers (
i32,i64etc.), unsigned integers (u32,u64etc.), floating-point numbers (f32,f64etc.), boolean (bool), character (char). - Composite types: arrays (
[]T), structs (struct), enums (enum), unions (union), tuples ([]const T). - Pointers and references: pointers (
*T), references (&T), optional types (?T). - Function types:
fn(...) -> R.
Variable Naming Rules
Zig variable naming follows some basic rules, including:
-
Variable names must start with a letter or underscore.
-
Variable names can contain letters, digits, and underscores.
-
Variable names are case-sensitive.
-
Variable names cannot be Zig keywords (such as
var,const,fnetc.).
Example
var my_var
:
i32
=
10
;
// Valid variable names
var _value
:
f64
=
3.14
;
// Valid variable names
var 1var
:
i32
=
10
;
// Invalid variable names
Type Inference
Zig supports type inference. If a variable is initialized at definition, the compiler can infer the variable's type from the initial value.
Example
var x
=
10
;
// The compiler infers the type of x as comptime_int
var y
=
3.14
;
// The compiler infers the type of y as comptime_float
var z
=
"Hello"
;
// The compiler infers the type of z as *const [5:0]u8
Scope
The scope of a variable is determined by where it is defined.
In Zig, variables can be defined in global scope, local scope, and block scope.
Global scope - Global variables can be accessed anywhere in the program.
Example
const
std
=
@import
(
"std"
)
;
const
g
:
i32
=
90
;
// Global constant
pub fn main
(
)
void
{
std.
debug
.
(
"g: {}\n"
, .
{
g
}
)
;
}
Local scope - Local variables can only be accessed within the function or code block where they are defined.
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
var h
:
i32
=
100
;
// Local variable
{
var i
:
i32
=
110
;
// block-scope variable
std.
debug
.
(
"i: {}\n"
, .
{
i
}
)
;
}
// std.debug.print("i: {}\n", .{i}); // This line causes a compile error because i is not in the scope of the main function
std.
debug
.
(
"h: {}\n"
, .
{
h
}
)
;
}
Type Conversion
Zig provides type conversion functions to convert one type to another.
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
const
j
:
i32
=
120
;
const
k
:
f64
=
@intToFloat
(
f64, j
)
;
// Convert integer j to float k
std.
debug
.
(
"j: {}, k: {}\n"
, .
{
j, k
}
)
;
}
Default value
Variables must be initialized when defined, otherwise it will cause a compilation error.
Zig does not allow the use of uninitialized variables.
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
var l
:
i32
=
0
;
// Initialize variable l
std.
debug
.
(
"l: {}\n"
, .
{
l
}
)
;
}
Variable usage example
The following is a complete Zig program demonstrating variable definition and usage:
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
// Declare variable
var x
:
i32
=
10
;
var y
=
20
;
// Type inferred as comptime_int
// Modify the variable's value
x
=
30
;
y
=
40
;
// Output the variable's value
std.
debug
.
(
"x = {}\n"
, .
{
x
}
)
;
// Output: x = 30
std.
debug
.
(
"y = {}\n"
, .
{
y
}
)
;
// Output: y = 40
// Block-level scope
{
var z
:
i32
=
50
;
std.
debug
.
(
"z = {}\n"
, .
{
z
}
)
;
// Output: z = 50
}
// Here z is out of scope and cannot be accessed
}
Constant
In Zig, constants are defined using the const keyword.
Once a constant is defined, its value cannot be changed.
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
const
a
:
i32
=
10
;
// Define an integer constant a with value 10
std.
debug
.
(
"a: {}\n"
, .
{
a
}
)
;
}
Constant features:
-
Immutability: The value of a constant cannot be modified after it is defined.
-
Determined at compile time: The value of a constant must be determined at compile time and cannot be the result of a runtime computation.
-
Type Inference: If the constant's type is not explicitly specified, the compiler infers it from the initial value.
-
Naming Convention: Constants are typically named using uppercase letters and underscores (e.g.
MAX_SIZE) to distinguish them from variables.
Compile-time constants
Zig supports compile-time constants (comptime constants); their values are computed at compile time and can be used in compile-time logic.
Define compile-time constants
Use the comptime keyword to define compile-time constants.
Syntax:
comptime const constant_name: type = value;
For example:
comptime const MAX_SIZE: usize = 100; // 编译时常量
Feature
- Compile-time computation: The value of a compile-time constant is computed at compile time and can be used in compile-time logic (such as array size, type computation, etc.).
- Type safety: The type of a compile-time constant must be determined at compile time.
- ** Performance optimization:** Using compile-time constants can avoid runtime computation overhead.
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
comptime
const
SIZE
:
usize
=
10
;
// Compile-time constant
var arr
:
[
SIZE
]
i32
=
undefined
;
// Use compile-time constant to define array size
std.
debug
.
(
"Array size = {}\n"
, .
{
SIZE
}
)
;
// Output: Array size = 10
}
Differences between variables and constants
| Feature | Variable (var) |
Constant (const) |
Compile-time constant (comptime const) |
|---|---|---|---|
| Mutability | Mutable | Immutable | Immutable |
| Definition keyword | var |
const |
comptime const |
| Initialization requirement | Must be initialized | Must be initialized | Must be initialized |
| Type Inference | Supported | Supported | Supported |
| Scope | Block-level scope | Block-level scope | Block-level scope |
| Use Cases | Values that need to be modified | Values that do not need to be modified | Values computed at compile time |
Example
const
std
=
@import
(
"std"
)
;
pub fn main
(
)
void
{
// variable
var x
:
i32
=
10
;
x
=
20
;
std.
debug
.
(
"x = {}\n"
, .
{
x
}
)
;
// Output: x = 20
// Constant
const
PI
:
f64
=
3.14159
;
std.
debug
.
(
"PI = {}\n"
, .
{
PI
}
)
;
// Output: PI = 3.14159
// Compile-time constant
comptime
const
SIZE
:
usize
=
5
;
var arr
:
[
SIZE
]
i32
=
undefined
;
std.
debug
.
(
"Array size = {}\n"
, .
{
SIZE
}
)
;
// Output: Array size = 5
}