raz / site / content / tour / 11-defer.txt

107 lines · 2.6 KiB · raw · history · last change 3fee2db6

1title: Defer
2part: Go
3summary: Clean up beside the line that needs it, in the right order, on every way out.
4---
5```raz Defers run
6```
7
8`defer s;` runs `s` when the program leaves the statements the `defer` stands in: at their end, or by a `return`, a `break` or a `continue`. Deferred statements run the last first, and only those whose `defer` was reached. So a file is closed beside the line that opens it, however the procedure ends.
9
10## The order, and a `return` value
11
12A `return e;` evaluates `e` before the deferred statements run, so the value is what it was at the return.
13
14```raz Order run
15module Order;
16import Out;
17
18var counter: INT;
19
20proc next(): INT;
21begin
22 defer INC(counter);
23 return counter; (* the old value is returned; then counter grows *)
24end;
25
26proc nest;
27begin
28 defer Out.str("1 ");
29 defer Out.str("2 ");
30 defer Out.str("3 ");
31 Out.str("body: ");
32end;
33
34proc main*;
35var a, b: INT;
36begin
37 a := next();
38 b := next();
39 Out.int(a); Out.char(' '); Out.int(b); Out.char(' '); Out.int(counter); Out.ln;
40 nest;
41 Out.ln;
42end;
43
44end Order.
45```
46
47## In a loop
48
49A `defer` stands in the statement list that holds it, so in a loop body it runs at the end of each pass, and on a `break` or a `continue`.
50
51```raz Passes run
52module Passes;
53import Out;
54
55proc main*;
56var i: INT;
57begin
58 for i := 1 to 4 do
59 Out.str("pass "); Out.int(i);
60 defer Out.str(" done\n");
61 if i = 3 then break; end;
62 Out.str(" ...");
63 end;
64end;
65
66end Passes.
67```
68
69## Giving back what was taken
70
71The point is that acquiring and releasing sit next to each other, so a new early `return` added later can't leak. Here an arena and a buffer are both released on every path.
72
73```raz Report run
74module Report;
75import Out, Buf, Heap;
76
77(* a line, built in a buffer; false (nothing written) if n is negative *)
78proc line(n: INT): BOOL;
79var b: Buf.Buf;
80begin
81 if n < 0 then return false; end;
82 Buf.init(b, Heap.heap);
83 defer Buf.done(b); (* freed on every way out below *)
84 Buf.str(b, "n is ");
85 if n > 9 then
86 Buf.str(b, "large");
87 Out.str(Buf.bytes(b)); Out.ln;
88 return true;
89 end;
90 Buf.str(b, "small");
91 Out.str(Buf.bytes(b)); Out.ln;
92 return true;
93end;
94
95proc main*;
96begin
97 _ := line(3);
98 _ := line(30);
99 if not line(-1) then Out.str("rejected\n"); end;
100end;
101
102end Report.
103```
104
105## What defer does not do
106
107A deferred statement can't contain a `return`, `break` or `defer` that would leave it. A failed check, `Rt.exit` and `Sys.exit` end the program without running the deferred statements still pending, so deferred cleanup is for the program's resources, not for what must happen at exit; that is what `Rt.atExit` is for.