Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Zig Variables and Constants

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

.

print

(

"b: {}\n"

, .

{

b

}

)

;

}

Variable Characteristics

1. The Type Must Be Explicit:

Example

var x

:

i32

=

10

;

// Explicitly specify the type

var y

=

20

;

     

// The compiler infers the type as comptime_int

2. Mutability:

Example

var x

:

i32

=

10

;

x

=

20

;

// Modify the value of x

3. Scope:

Example

{

    var x

:

i32

=

10

;

    std.

debug

.

print

(

"x = {}\n"

, .

{

x

}

)

;

// Output: x = 10

}

// Here x is out of scope and cannot be accessed

4. Uninitialized Variables:

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:

Variable Naming Rules

Zig variable naming follows some basic rules, including:

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

.

print

(

"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

.

print

(

"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

.

print

(

"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

.

print

(

"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

.

print

(

"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

.

print

(

"x = {}\n"

, .

{

x

}

)

;

// Output: x = 30

    std.

debug

.

print

(

"y = {}\n"

, .

{

y

}

)

;

// Output: y = 40

   

// Block-level scope

   

{

        var z

:

i32

=

50

;

        std.

debug

.

print

(

"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

.

print

(

"a: {}\n"

, .

{

a

}

)

;

}

Constant features:


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

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

.

print

(

"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

.

print

(

"x = {}\n"

, .

{

x

}

)

;

// Output: x = 20

   

// Constant

   

const

PI

:

f64

=

3.14159

;

    std.

debug

.

print

(

"PI = {}\n"

, .

{

PI

}

)

;

// Output: PI = 3.14159

   

// Compile-time constant

    comptime

const

SIZE

:

usize

=

5

;

    var arr

:

[

SIZE

]

i32

=

undefined

;

    std.

debug

.

print

(

"Array size = {}\n"

, .

{

SIZE

}

)

;

// Output: Array size = 5

}