Basic Data Types

1
2
3
4
// ***** Arrays *****
// uses notation [num]type. num can be ignored.
const a = [5]u8{ 'h', 'e', 'l', 'l', 'o' };
const b = [_]u8{ 'w', 'o', 'r', 'l', 'd' };

Basic Control Flows

Control Flows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ***** if statements *****
// if () { block expression } else { block expression }
// if () inline-expression else inline-expression
var x : i32 = if (true) 1 else 2;

// while statement
// while (condition) : (update i) { expression }
// continue clause or break clause
var sum: i32 = 0;
var i : i32 = 0;
while (i <= 100) : (i += 1) {
sum += i;
}

// ***** for-loops *****
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };
for (string, 0..) |character, index| {
_ = character;
_ = index;
}
for (string) |character| {
_ = character;
}
for (string, 0..) |_, index| {
_ = index;
}
for (string) |_| {}

Defer

defer keyword is used to execute a command upon exiting the current block. When multiple defers exist, they’re executed in the reversed order

1
2
3
4
5
6
7
8
9
10
const expect = @import("std").testing.expect;

test "multi defer" {
var x: f32 = 5;
{
defer x += 2;
defer x /= 2;
}
try expect(x == 4.5);
}