Zig Basic Syntax
Zig is a new programming language, designed to be simple, efficient, and directly compatible with C.
Below are some basic syntax introductions to Zig to help you get started quickly.
Zig code files have the .zig extension.
* * *
## First Zig Program
Let's first look at Zig's "Hello, World!" program.
Let's initialize a Zig project first:
mkdir hello-world cd hello-world zig init
Then create hello.zig file in the project, code as follows:
## 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 standard library:
const std = @import("std");
This line imports Zig's standard library, similar to `#include ` in C.
2. Define main function:
pub fn main() !void
The `pub` keyword indicates that this function is public, the `fn` keyword is used to define functions, and `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 (the `!` prefix indicates an error union type).
3. Get standard output:
const stdout = std.io.getStdOut().writer();
Obtains the writer for standard output through the standard library, and subsequently calls its methods to write content.
4. Print "Hello, World!":
try stdout.print("Hello, World!n", .{});
The `print` method writes a formatted string to standard output, `.{}` is an empty argument list. The `try` keyword propagates errors upward to the caller when an error occurs.
This program demonstrates some basic features of the Zig language, such as function definitions, 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 in terminal:
./hello
This will output:
Hello, World!
## Identifiers
In Zig language, identifiers are names used to name variables, functions, types, etc.
Here are some rules and features about Zig identifiers:
1. **Letters and Numbers**: Identifiers can contain letters (A-Z and a-z), numbers (0-9), and underscores (_).
2. **Starting Character**: Identifiers must start with a letter or underscore, not with a number.
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` (structure), `if` (conditional statement), etc.
5. **Naming Conventions**: Zig officially recommends the following conventions:
* **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`.
6. **Optional Type**: Zig has a special type `?T`, which represents an optional value of type `T`. This is very useful when dealing with values that may be null.
7. **Compile-Time Constants**: Using the `comptime` keyword before an identifier indicates that the identifier is a compile-time constant.
8. **Error Type**: Using the `error` keyword can define error types, for example:
pub fn openFile(path: []const u8) !void { // ...}
9. **Type Suffix**: Using the `_t` suffix after type names is a C language convention, which can also be done in Zig but is not required.
## Reserved Keywords
Here are some reserved keywords in Zig:
| Keywords | Description |
| --- | --- |
| `align` | Specifies the number of bytes for variable or type alignment |
| `allowzero` | Allows pointers to point to null values |
| `and` | Logical AND operation |
| `asm` | Inline assembly block |
| `break` | Break out of the nearest loop or scope |
| `callconv` | Calling convention |
| `const` | Define constants |
| `continue` | Continue to the next loop iteration |
| `defer` | Deferred statement execution until scope exits |
| `else` | Negative branch of conditional statement |
| `enum` | Enumeration type |
| `errdefer` | Deferred execution statement on error |
| `error` | Error type definition |
| `export` | Export symbol for C language calls |
| `fn` | Function definition |
| `for` | Iteration loop |
| `if` | Conditional statement |
| `inline` | Inline function or inline loop |
| `linksection` | Specify linker section |
| `noalias` | Pointers cannot be aliased by other pointers |
| `noinline` | Prevent function inlining |
| `null` | Null value for optional type |
| `or` | Logical OR operation |
| `packed` | Remove struct padding, pack tightly by bits |
| `pub` | Public access level |
| `return` | Return from function |
| `struct` | Struct type definition |
| `switch` | Multi-way branch selection statement |
| `test` | Test code block |
| `threadlocal` | Thread-local variable |
| `try` | Try to execute expression, propagate error upward on failure |
| `union` | Union type definition |
| `usingnamespace` | Import all public members of namespace into current scope |
| `var` | Define mutable variable |
| `void` | No type, commonly used for functions with no return 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; // Define an integer constant x with value 10var y: f64 = 3.14; // Define a floating-point variable y with value 3.14
### 2. Functions
Functions are defined using the `fn` keyword and specify a return type.
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 positiven", .{}); } else { try stdout.print("Number is not positiven", .{}); }}
### 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 loop, iterate through array const array = i32{ 1, 2, 3, 4, 5 }; for (array) |item| { try stdout.print("item: {}n
YouTip