tomiis4/Zig
My Zig projects with cheatsheet
zig run file.zig
zig build-exe file.zig
// import print fromm std
const print = @import("std").debug.print;
// create main function
pub fn main() void {
// print
print("Hello, world!\n", .{});
}
const <package> = @import("<package-name>");
// mutable
var <variable-name>: type = <value>;
var <variable-name>: type; // empty
// immutable
const <variable-name>: type = <value>;
// arrays
var arr: [<length>]<type> = [<value>, ...];
var arr: [<length>]<type>; // empty
/*
Type:
bool = %b = true, false
u8, u16, u32, u64, u128 = %d = number in range of x bits, can't be negative
i8, i16, i32, i64, i128 = %d = number in range of x bits, can be negative
f16, f32, f64 = %f = decimal numbers
[] u8 = %.*s = string
*/
// create struct
const <Struct-name> = struct {
<key1>: <type>,
<key2>: <type>,
};
// use struct
const <struct-x> = {
<key1>: <value>,
<key2>: <value>,
};
const HashMap = @import("std").HashMap;
// create map
var <map-name> = HashMap(<type>).init(<length>);
// add item
<map-name>.put(<key>, <value>);
// read item
const <value> = <map-name>.get(<key>);
// normal function for one file
fn name() void {
//...
}
// public function
pub fn name() void {
//...
}
// return
fn name() <type> { return x; }
fn name() (<type>, <type>) { return (x, y); }
// parameters
fn name(param1: <type>) { }
fn name(param1, param2: <type>) { } // if param1 have same type as param2
if (<statement>) {
// ...
}
switch (operation) {
x => <do-x>,
y => <do-y>,
else => <do-else>,
}
for (var i: u32 = 0; i<10; i++) {
// ...
}
var arr: [10]u8 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (arr) |elem, i| {
// ...
}
while (condition) {
// ...
}
// str -> int
const str = "123";
const num = try std.parseInt(u32, str);
// int -> str
// main.zig
// main_test.zig
// folder structure
|- main.zig
|
|- example
|- second.zig
// main.zig
// second.zig
// code
Enums
std.io