Cleaning up#
Files, sockets and processes need closing, even when the function leaves early because something failed. In Manuscript you do not write the close. A value that owns a resource closes it when its scope ends.
import (
lines from "@std/io/steps.ms",
collect from "@std/io/streams.ms",
open from "@std/os/fs.ms",
)
fn count_orders(path String) Int! {
file := open(path)?
rows := collect(file.reader()? | lines)?
if rows.is_empty() {
return error(Error(f"{path} is empty", kind: "EBADMSG"))
}
return ok(rows.length() - 1)
}
fn main() Void! {
count := count_orders("orders.csv")?
print(f"{count} orders")
}2 ordersRun it next to an orders.csv file containing a header and two rows. With an empty orders.csv, it prints error: orders.csv is empty to standard error and exits with 1.
What to notice#
openreturns a file handle. Binding it withfile := ...is all it takes: the handle closes whencount_ordersreturns, on the normal path and on every?orreturn error(...)before it.- If
openitself fails, there is nothing to close and the error goes to the caller. - Cancellation and runtime faults close it as well. You cannot forget a close by returning early.
file.reader()? | linespipes the byte stream intolines(|passes the left value into the next step), andcollectreads the lines into a list.- Scopes nest. Inner resources close before outer ones, and in one scope the last declared closes first.
When you need to close early#
Declare the binding with var and call close() when you are done reading but not yet done with the function. A second close is harmless:
var file = open(path)?
head := file.read_lines(max_lines: 1)?
void file.close()
slow_work(head)close() returns a Result, because closing can fail. Flush output before you close it so delivery errors reach you: output.flush()?. ms check --only lint warns when a scope-closed resource has an uncalled flush.
Next: Doing things at once . Exact rules: Scope-end cleanup .