Getting Started with Zig Programming Language: A Guide with Examples
40 views
Sure! Below are a few examples to help you get started with the Zig programming language. Zig is known for its simplicity and performance.
- Hello World:
const std = @import("std");
pub fn main() void {
const stdout = std.io.getStdOut().writer();
stdout.print("Hello, World!\n", .{}) catch unreachable;
}
- Variables and Types:
const std = @import("std");
pub fn main() void {
var x: i32 = 10;
var y: f64 = 20.5;
const stdout = std.io.getStdOut().writer();
stdout.print("x: {}, y: {}\n", .{x, y}) catch unreachable;
}
- Functions:
const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const result = add(5, 7);
const stdout = std.io.getStdOut().writer();
stdout.print("Result: {}\n", .{result}) catch unreachable;
}
- Simple For Loop:
const std = @import("std");
pub fn main() void {
const stdout = std.io.getStdOut().writer();
for (std.range(0, 5)) |i| {
stdout.print("i: {}\n", .{i}) catch unreachable;
}
}
- Conditional Statements:
const std = @import("std");
pub fn main() void {
var x: i32 = 10;
const stdout = std.io.getStdOut().writer();
if (x > 5) {
stdout.print("x is greater than 5\n", .{}) catch unreachable;
} else if (x < 5) {
stdout.print("x is less than 5\n", .{}) catch unreachable;
} else {
stdout.print("x is equal to 5\n", .{}) catch unreachable;
}
}
- Array and Looping:
const std = @import("std");
pub fn main() void {
var array: [5]i32 = [5]i32{1, 2, 3, 4, 5};
const stdout = std.io.getStdOut().writer();
for (array) |element| {
stdout.print("Element: {}\n", .{element}) catch unreachable;
}
}
- Structs:
const std = @import("std");
const Point = struct {
x: i32,
y: i32,
};
pub fn main() void {
var p = Point{ .x = 10, .y = 20 };
const stdout = std.io.getStdOut().writer();
stdout.print("Point: x = {}, y = {}\n", .{p.x, p.y}) catch unreachable;
}
These examples demonstrate basic features like printing to the console, working with variables and types, conditional statements, loops, arrays, functions, and structs. You can extend these examples to experiment with more Zig features.