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

134 lines
2.4 KiB

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
test "if expression" {
const a = 1;
const b = 2;
const c = if (@rem(a + b, 2) == 0) 100 else 200;
testing.expectEqual(c, 200);
}
test "if boolean" {
const a = 1;
const b = 2;
if (a + b == 100) {
unreachable;
} else if (a + b == 3) {
testing.expect(true);
} else {
unreachable;
}
}
test "if optional" {
var number: ?i32 = null;
if (number == null)
testing.expect(true);
if (number) |_| {
unreachable;
} else {
testing.expect(true);
}
number = 42;
if (number) |e| {
testing.expectEqual(e, 42);
} else unreachable;
if (number) |e| {
testing.expectEqual(e, 42);
}
if (number) |*e| {
e.* += 100;
}
testing.expectEqual(number.?, 142);
}
test "if error union" {
var number: anyerror!i32 = error.Nan;
if (number) {} else |err| {
testing.expectEqual(err, error.Nan);
}
// same as above
if (number) |_| {} else |err| {
testing.expectEqual(err, error.Nan);
}
if (number) |_| {
unreachable;
} else |err| {
testing.expectEqual(err, error.Nan);
}
number = 42;
if (number) |e| {
testing.expectEqual(e, 42);
} else |_| {
unreachable;
}
testing.expectEqual(try number, 42);
// this does not work
//if (number) |e| {
// testing.expectEqual(e, 42);
//} else {
// unreachable;
//}
if (number) |*e| {
e.* += 100;
} else |_| {
unreachable;
}
testing.expectEqual(try number, 142);
}
test "if error union with optional" {
var number: anyerror!?i32 = error.SomeError;
if (number) |_| {} else |err| {
testing.expectEqual(err, error.SomeError);
}
number = 42;
if (number) |e| {
testing.expectEqual(e, 42);
} else |_| {
unreachable;
}
testing.expectEqual(try number, 42);
if (number) |*e| {
e.*.? += 100;
} else |_| {
unreachable;
}
testing.expectEqual(try number, 142);
if (number) |*me| {
if (me.*) |*e| {
e.* -= 100;
}
} else |_| {
unreachable;
}
testing.expectEqual(try number, 42);
number = null;
if (number) |e| {
testing.expectEqual(e, null);
} else |_| {
unreachable;
}
}