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/operators.zig

70 lines
2.2 KiB

const std = @import("std");
const debug = std.debug;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
// Zig does not have any operator overloading.
test "overflow" {
var x: u32 = math.maxInt(u32);
// overflow
//x += 1;
debug.print("{}\n", .{x});
x +%= 1; // wraoping
testing.expect(x == math.minInt(u32));
// overflow
var y: u32 = math.minInt(u32);
//y -= 1;
debug.print("{}\n", .{y});
y -%= 1; // wrapping
testing.expect(y == math.maxInt(u32));
}
test "optionals" {
// this is made var instead of const to trigger the unreachable error. If it were const, then the
// compiler can figure out that this is definitely null, and so we would get a different error.
var number_or_null: ?i32 = null;
const value = number_or_null orelse 99;
testing.expect(value == 99);
//debug.print("{}\n", .{number_or_null.?});
const another_number_or_null: ?i32 = 42;
const another_value = another_number_or_null orelse 99;
testing.expect(another_value == 42);
testing.expect(another_number_or_null.? == 42); // equivalent to another_number_or_null orelse unreachable
}
test "error unions" {
var error_or_string: anyerror![]const u8 = error.SomethingAwful;
var string_val = error_or_string catch "hola";
testing.expect(mem.eql(u8, "hola", string_val));
string_val = error_or_string catch |err| "mundo";
testing.expect(mem.eql(u8, "mundo", string_val));
error_or_string = "hello";
string_val = error_or_string catch "hola";
testing.expect(mem.eql(u8, "hello", string_val));
}
// this is only available when the arrays are known at comptime
test "array concatenation" {
const arr1 = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
const arr2 = [_]u8{ ',', ' ', 'w', 'o', 'r', 'l', 'd' };
const arr3 = arr1 ++ arr2;
testing.expect(mem.eql(u8, "hello, world", &arr3));
}
// again, this only works when the arrays are comptime
test "array multiplication" {
const pattern = "nope" ** 10;
testing.expect(mem.eql(u8, "nopenopenopenopenopenopenopenopenopenope", pattern));
}
test "pointers" {
var x: i32 = 21;
var ptr = &x;
ptr.* += ptr.*;
testing.expect(ptr.* == 42);
testing.expect(x == 42);
}