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

Zig basic syntax

Zig basic syntax

Zig is a new programming language designed to be simple, efficient, and directly compatible with C.

Below are some introductions to Zig's basic syntax to help you get started quickly.

Zig code files have the .zig extension.


The first Zig program

Let us first look at Zig's "Hello, World!" program.

Let us first initialize a zig project:

mkdir hello-world
cd hello-world
zig init

Then create the hello.zig file under this project, with the following code:

Example (hello.zig file)

const

std

=

@import

(

"std"

)

;

pub fn main

(

)

!

void

{

   

const

stdout

=

std.

io

.

getStdOut

(

)

.

writer

(

)

;

   

try

stdout

.

print

(

"Hello, World!\n"

, .

{

}

)

;

}

Code analysis:

1. Import the standard library:

const std = @import("std");

This line of code imports Zig's standard library, similar to in C language #include .

2. Define the main function:

pub fn main() !void

pub The keyword indicates this function is public,fn The keyword is used to define a function,main is the entry point of the function. The return type !void indicates that the function does not return a value, but may return an error (! prefix indicates an error union type).

3. Get standard output:

const stdout = std.io.getStdOut().writer();

Obtain the writer for standard output through the standard library, and call its methods later to write content.

4. Print "Hello, World!":

try stdout.print("Hello, World!\n", .{});

print The method writes a formatted string to standard output,.{} is an empty parameter list.try The keyword propagates the error to the caller when an error occurs.

This program demonstrates some basic features of the Zig language, such as function definition, standard library usage, and error handling.

If you just want to run a single file, you can directly use:

zig run hello.zig

If you want to compile to an executable file, use:

zig build-exe hello.zig

After compilation, run it in the terminal:

./hello

This will output:

Hello, World!

Identifiers

In the Zig language, an identifier is a name used to name variables, functions, types, etc.

The following are some rules and characteristics about Zig identifiers:

  1. Letters and numbers: Identifiers can contain letters (A-Z and a-z), digits (0-9), and underscores (_).

  2. Leading character: An identifier must start with a letter or underscore, not with a digit.

  3. Case Sensitive: Zig is a case-sensitive language, which means Variable and variable are two different identifiers.

  4. Keywords and reserved words: Some specific words are reserved in Zig and cannot be used as identifiers. For example fn(function),struct(struct),if(conditional statement), etc.

  5. Naming conventions: Zig officially recommends the following conventions:

  6. camelCase: Used for variable names and function names. For example myVariable, calculateSum.
  7. PascalCase: Used for type names and namespaces. For example Point, ArrayList.
  8. SCREAMING_SNAKE_CASE: Used for constants known at compile time (comptime constants). For example MAX_SIZE.
  9. - **camelCase:** Used for variable names and function names. For example `myVariable`, `calculateSum`. - **PascalCase:** Used for type names and namespaces. For example `Point`, `ArrayList`. - **SCREAMING_SNAKE_CASE:** Used for constants known at compile time (comptime constants). For example `MAX_SIZE`.
    1. Optional types: Zig has a special type ?T, representing an optional value of type T . This is very useful when handling values that may be null.

    2. Compile-time constants: Use the comptime keyword before an identifier to indicate that the identifier is a compile-time constant.

    3. Error types: When using error The keyword can define an error type, for example:

      pub fn openFile(path: []const u8) !void {
       // ...
      

    } 9.

    Type suffix: Use the _t suffix after the type name, which is a C language habit and can also be done in Zig, but is not required.

    Reserved keywords

    The following are some reserved keywords of the Zig language:

    Keywords Description
    align Specify the alignment byte count for a variable or type
    allowzero Allow a pointer to point to a null value
    and Logical AND operation
    asm Inline assembly block
    break Break out of the nearest loop or scope
    callconv Calling convention
    const Defining Constants
    continue Continue to the next loop iteration
    defer Defer execution of a statement until the scope exits
    else The negative branch of a conditional statement
    enum Enumeration Type
    errdefer Deferred execution statement when an error occurs
    error Error type definition
    export Export a symbol for calling from C and other languages
    fn Function definition
    for Iterate loop
    if Conditional statement
    inline Inline function or inline loop
    linksection Specify the section for the linker
    noalias A pointer cannot be aliased by other pointers
    noinline Prevent function inlining
    null The null value of an optional type
    or Logical OR operation
    packed Cancel struct padding and pack tightly by bits
    pub Public access level
    return Return from a function
    struct Struct type definition
    switch Multi-way branch selection statement
    test Test code block
    threadlocal Thread-local variable
    try Try to execute an expression, propagating up on error
    union Union type definition
    usingnamespace Introduce all public members of a namespace into the current scope
    var Define a mutable variable
    void Untyped, often used when a function returns no value
    while Loop statement

    Basic Syntax

    1. Variables and constants

    In Zig, variables are defined using the var keyword, and constants are defined using the const keyword.

    
    const x: i32 = 10;  // 定义一个整数常量 x,值为 10
    var y: f64 = 3.14;  // 定义一个浮点数变量 y,值为 3.14
    

    2. Functions

    Function usage fn Defined using a keyword, with the return type specified.

    
    const std = @import("std");
    
    fn add(a: i32, b: i32) i32 {
        return a + b;
    }
    
    pub fn main() !void {
        const result = add(3, 4);
        const stdout = std.io.getStdOut().writer();
        try stdout.print("Result: {}\n", .{result});
    }
    

    3. Conditional Statements

    Use if and else to implement conditional logic.

    
    const std = @import("std");
    
    pub fn main() !void {
        const stdout = std.io.getStdOut().writer();
        const number = 10;
        if (number > 0) {
            try stdout.print("Number is positive\n", .{});
        } else {
            try stdout.print("Number is not positive\n", .{});
        }
    }
    

    4. Loops

    Zig supports while and for loops.

    
    const std = @import("std");
    
    pub fn main() !void {
        const stdout = std.io.getStdOut().writer();
    
        // while loop, : (i += 1) is the update expression executed after each iteration
        var i: i32 = 0;
        while (i < 5) : (i += 1) {
            try stdout.print("i: {}\n", .{i});
        }
    
        // for 循环,遍历数组
        const array = [5]i32{ 1, 2, 3, 4, 5 };
        for (array) |item| {
            try stdout.print("item: {}\n", .{item});
        }
    }
    

    5. Structs

    Zig uses struct to define structs.

    
    const std = @import("std");
    
    const Point = struct {
        x: i32,
        y: i32,
    };
    
    pub fn main() !void {
        const stdout = std.io.getStdOut().writer();
        const p = Point{ .x = 10, .y = 20 };
        try stdout.print("Point: ({}, {})\n", .{ p.x, p.y });
    }
    

    6. Error Handling

    Zig uses error enum types and try / catch the keyword to perform error handling.

    
    const std = @import("std");
    
    const FileError = error{
        FileNotFound,
    };
    
    fn readFile(path: []const u8) !void {
        // Simulate a potentially failing operation
        if (std.mem.eql(u8, path, "invalid")) {
            return FileError.FileNotFound;
        }
        // Other operations...
    }
    
    pub fn main() !void {
        const stdout = std.io.getStdOut().writer();
    
        readFile("invalid") catch |err| {
            switch (err) {
                FileError.FileNotFound => {
                    try stdout.print("Error: File not found\n", .{});
                },
                else => return err,
            }
            return;
        };
    
        try stdout.print("File read successfully\n", .{});
    }
    

    Code analysis: