Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/comptime.zig

33 lines
839 B

const std = @import("std");
const testing = std.testing;
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
fn biggerString(a: []const u8, b: []const u8) []const u8 {
return if (max(usize, a.len, b.len) == a.len) a else b;
}
test "comptime parameters" {
testing.expectEqual(max(u32, 11, 2), 11);
testing.expectEqual(max(i32, -2, 3), 3);
testing.expectEqual(max(f64, 1.23, 2.234), 2.234);
testing.expectEqual(biggerString("hello", "world"), "hello");
testing.expectEqual(biggerString("hola", "mundo"), "mundo");
}
fn factorial(n: u32) u32 {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
test "comptime factorial" {
comptime {
testing.expectEqual(factorial(5), 120);
testing.expectEqual(factorial(10), 3628800);
}
}