Chapter 3 of 8
No null, no exceptions
A value that may be missing is an Option. An operation that may fail returns a Result. ? passes the failure up.
tin run examples/05-errors.tin// No null, no exceptions. A value that may be missing is an Option<T>;
// an operation that may fail returns a Result<T, E>.
// `?` unwraps the good case or returns the bad one to the caller.
type Config = { host: string, port: int }
fn parsePort(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
None => Err("'{text}' is not a number")
}
}
fn parseConfig(line: string): Result<Config, string> {
let parts = line.split(":")
if parts.len != 2 { return Err("expected host:port, got '{line}'") }
let port = parsePort(parts[1])?
Ok(Config { host: parts[0], port })
}
fn main() {
for line in ["localhost:8080", "example.com:http", "example.com:99999", "nonsense"] {
match parseConfig(line) {
Ok(c) => print("ok {c.host} on port {c.port}")
Err(why) => print("error {why}")
}
}
// Option has the same shape, for "nothing there" rather than "went wrong"
var ages: Map<string, int> = newMap()
ages.set("ada", 36)
print(ages.get("ada"))
print(ages.get("bob"))
print(ages.get("bob").or(0))
} ok localhost on port 8080
error 'http' is not a number
error port 99999 is out of range
error expected host:port, got 'nonsense'
Some(36)
None
0 Because failures are values, they show up in the types. A caller can't forget that
parseConfig can fail: the only way to get at the Config is to handle the
Err or pass it on with ?. The same idea carries into agents: a tool that
returns Err doesn't crash the program, it tells the model the call failed.