Lesson 11 of 56 · Functions
defer and function modifiers
defer keeps cleanup next to the code that needs it, so it cannot be forgotten on an early return. The function modifiers tell the compiler how a function behaves, and some of them it checks for you.
defer
A statement written after defer does not run where it stands. It runs when the surrounding block ends. With several defers, the last one runs first, the way you undo steps in reverse order. The commonest use is releasing something right beside the line that acquired it.
func work():
println "starting work"
defer println "first cleanup"
defer println "second cleanup"
println "doing the work"
end
func main:
work()
println "after the work"
endstarting work doing the work second cleanup first cleanup after the work
Every way out
A deferred statement runs whichever way the block is left: at its end, at a ret in the middle, or at a break out of a loop. That is the whole point. A function with several ret statements needs one defer, not a copy of the cleanup before each ret.
func find(items: int[], wanted: int): int:
defer println "search for", wanted, "finished"
each i, item in items:
if item == wanted:
ret i
end
end
ret -1
end
func main:
codes := [404, 200, 500]
println "position:", find(codes, 200)
println "position:", find(codes, 301)
endsearch for 200 finished position: 1 search for 301 finished position: -1
The deferred line runs after the result has been worked out but before the caller gets it, so it is printed before position:. The same holds in main: a ret 1 still runs main's defers, which is why os.Exit is not allowed there.
defer belongs to its block
A defer runs at the end of the block it is written in, not at the end of the function. Inside a loop that means at the end of every round, and inside an if at the end of that branch.
func main:
repeat 3 in day:
defer println " close day", day
println "open day", day
end
late := 2
if late > 0:
defer println " report sent"
println "late orders:", late
end
println "done"
endopen day 0 close day 0 open day 1 close day 1 open day 2 close day 2 late orders: 2 report sent done
So something acquired inside a loop body and deferred there is released before the next round starts, which is usually exactly what you want.
When the values are read
A deferred statement reads its variables when it runs, not when the defer line is reached. If a variable changes in between, the defer sees the new value. To keep the value from the moment of the defer, copy it into another variable first.
func main:
mut stage := "start"
defer println "deferred sees:", stage
saved := stage
defer println "saved copy:", saved
stage = "finish"
println "stage now:", stage
endstage now: finish saved copy: start deferred sees: finish
Freeing collections
A Vector or a HashMap takes memory that you give back with free(). Write defer x.free() on the line right after creating it, and every path out of the function frees it, including the early ret 0 here.
func average_reading(raw: int[]): int:
mut valid := Vector {} as Vector<int>
defer valid.Free()
each r in raw:
if r >= 0:
valid.Push(r)
end
end
if valid.Len() == 0:
ret 0
end
mut sum := 0
each v in valid:
sum += v
end
ret sum / valid.Len()
end
func main:
println average_reading([21, -1, 23, 25, -1])
println average_reading([-1, -1])
end23 0
The collections lesson covers Vector and HashMap, and the memory lesson explains what needs freeing and why.
Closing files
The same pattern closes files. Check that the open worked, then defer the close straight away; the code that follows may return early without leaving the file open. Here main also defers deleting the temporary file, so it is gone when the program ends.
import os
func save_report(path: str, total: int): bool:
f := os.Open(path, "w")
if f == null:
ret false
end
defer f.Close()
f.Write("total: " + total + "\n")
f.Write("status: paid\n")
ret true
end
func main:
path := os.TempDir() + "/salam-report.txt"
if not save_report(path, 245):
printerrln "cannot write", path
ret 1
end
defer os.Remove(path)
print os.ReadFile(path)
endtotal: 245 status: paid
A defer may call a function that returns a value, as os.Remove does; the value is simply dropped. There is no block form defer: ... end. When the cleanup takes several steps, put them in a function and defer the call.
Function modifiers
These words go before func and say something about the function. Some are promises the compiler checks, others are hints:
| Modifier | Meaning | What the compiler does |
|---|---|---|
pure | No side effects: the result depends only on the arguments | Rejects printing, writing a global or calling an impure function inside it |
inline | Place the body at the call site | Takes it as a hint, useful for small functions called very often |
noinline | Keep it a real call | Takes it as a hint, handy when profiling or debugging |
noret | The function never returns, for example it ends the program | Treats code after a call to it as unreachable |
deprecated | The function is obsolete | Warns at every call (W013) |
pub | Visible outside its package | See the packages lesson |
pure func net_price(price: int, discount: int): int:
ret price - price * discount / 100
end
inline func square(n: int): int:
ret n * n
end
noinline func receipt_line(name: str, amount: int): str:
ret name + ": " + amount
end
func main:
println net_price(200, 15), square(9)
println receipt_line("tea", net_price(90, 10))
end170 81 tea: 81
Add a println to net_price and the build stops with "'pure' function 'net price' cannot call 'println': it has side effects". That check is what makes pure worth writing: a pure function is safe to call anywhere, any number of times.
import os
noret func fail(message: str):
printerrln "error:", message
os.Exit(2)
end
func check_age(age: int): int:
if age < 0 or age > 150:
fail("impossible age " + age)
end
ret age
end
func main:
println check_age(34)
end
pub deprecated func old_total(a: int, b: int): int:
ret a + b
end34
Called with an age of -3, check_age prints "error: impossible age -3" and the program exits with code 2. Because fail is noret, the compiler knows the call never comes back, and a statement written right after it is rejected as unreachable (E070). It does not check the body, though: a noret function that does return crashes the program, so make sure it always ends in os.Exit or another call that never returns. old_total is marked deprecated, so any call to it is reported as W013, and warnings are errors: the build stops until the caller moves to the replacement.
Rules of thumb
Write the defer on the line right after you acquire the thing it releases.
Defers run in reverse order, at the end of their own block.
A deferred statement sees the values its variables have when it runs.
Mark a function pure when it is, and let the compiler keep it that way.
Use noret only for functions that really end the program.