This commit is contained in:
2026-01-19 05:43:29 +09:00
parent 40f41a4fd0
commit 0f6fddd794
36 changed files with 1724 additions and 0 deletions

24
guide/language/defer.zig Normal file
View File

@@ -0,0 +1,24 @@
const expect = @import("std").testing.expect;
test "defer" {
var x: i16 = 5;
{
defer x += 2;
try expect(x == 5);
}
try expect(x == 7);
}
test "multi defer" {
var x: f32 = 5;
{
// When there are multiple defers in a single block, they are executed in reverse order.
defer x += 2;
defer x /= 2;
}
try expect(x == 4.5);
}
// Defer is useful to ensure that resources are cleaned up when they are no longer needed.
// Instead of needing to remember to manually free up the resource,
// you can add a defer statement right next to the statement that allocates the resource.