Zig Basic Syntax
This chapter introduces the basic syntax rules of the Zig language, laying a solid foundation for subsequent learning.
Program Structure
The Simplest Zig Program
Let's analyze each part of this program:
const std = @import("std");- Import the standard librarypub fn main() void- Define a public main function with void return typestd.debug.print()- Call the standard library's print function.{}- Empty parameter tuple
Comments
Single-line Comments
Documentation Comments
Top-level Documentation Comments
Identifiers
Naming Rules
- Start with a letter or underscore
- Can contain letters, numbers, underscores
- Case-sensitive
Naming Conventions
Keywords
Zig keywords cannot be used as identifiers:
Statements and Expressions
Statements
Statements perform operations but don't return values:
Expressions
Expressions evaluate and return values:
Semicolon Rules
Semicolons are optional in Zig, but there are specific rules:
Code Blocks
Use curly braces {} to define code blocks:
Operators
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Literals
Integer Literals
Float Literals
Character Literals
String Literals
Escape Sequences
Array and Slice Literals
Struct Literals
Function Call Syntax
Error Handling Syntax
Optional Type Syntax
Compile-time Syntax
Code Example: Comprehensive Syntax Demonstration
Syntax Best Practices
1. Maintain Consistent Indentation
2. Reasonable Use of Blank Lines
3. Appropriate Comments
Summary
This chapter introduced Zig's basic syntax rules, including:
- ✅ Program structure and comments
- ✅ Identifiers and keywords
- ✅ Operators and literals
- ✅ Basic syntax structures
- ✅ Code style recommendations
After mastering these basic syntax elements, you can start writing simple Zig programs. In the next chapter, we'll learn about variable declarations in Zig.