Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
The languages used in make
bun
which is faster thannode
anddeno
- import are declared with
@import("<name>")
function to a variable - functions
<access> fn <name>(<args>) <return type> {
<body>;
}
-
seperated by
;
-
main
function should be a public -
zig is explicitly typed -> more control
-
there is standard library like all other languages for thing like printing and I/O
const std = @import("std");
pub fn main() void {
std.debug.print("Hello", .{});
// ^^
// debug.print takes two arguments
}
Basically to types:
var
which is mutable variableconst
which is immutable after assigning
<type> <var_name> [: <data_type>] = <value>
as of <data_type>
there are total ~34 primitive dypes
- signed (int, float [8,16,32,64])
- unsigned
- pointer (usize, isize)
- C ABI compatible types [shor, long, int, uint, ulog, longlong, ulonglong, longdouble]
// string
const name = "saicharan";
// int ( u8 )
const age: u8 = 18;
// arrays ( u16 )
const arr: [3]u8 = [3]u32{1,3,4};
var arr2 = [_]u8{1,2,4};
printing those
const std = @import("std");
pub fn main() void {
const name = "saicharan";
const age: u8 = 18;
std.debug.print("My name is {s}, and iam {u8} old", .{name, age});
// ^ ^
// string u8
// specifier specifier
}
unused variable result in compilation error
they are same mostly ( just like other languages )
- Logical
- if
- else
- Loops
- while
- for
const std = @import("std");
pub fn main() void {
var num: u8 = 1;
// normal if-else
if ( num == 1 ) {
num+= 1;
}
else {
num-= 1;
}
const res = if (num == 2) "its 2 broo" else "what ?";
// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
// (in line if-else)
std.debug.print("==|> {s}", .{res});
}
loops are a little different than other languages, both while
and for
have extra features
const std = @import("std");
pub fn main() void {
var num: u16 = 1;
// normal while loop
while (num != 10) {
num += 1;
std.debug.print("-> N: {},\r\n", .{num});
}
// extra feture
while (num != 20): (num+=1) {
std.debug.print("-> N: {},\r\n", .{num});
}
// also in one line :)
while (num != 30): (num += 2) std.debug.print("-> N: {},\r\n", .{num});
}
const std = @import("std");
pub fn main() void {
const num_arr = [_]u8{1,2,3,4,5,5,6};
for (num_arr) |num, index| {
std.debug.print("{}->{}\n", .{index, num});
}
}