Learn Tin · Part 1: The language · Chapter 7
Option, Result and ?
No null and no exceptions: missing values and failures are ordinary values.
Tin has no null and no exceptions. Both are replaced by two ordinary sum types from the last
chapter, and you already know how to use those: with match.
Maybe a value: Option
A function that may have nothing to give back returns Option<T>: Some(value)
or None.
tin run option.tin// Option<T> is Some(value) or None. There is no null.
fn findUser(id: int): Option<string> {
if id == 1 { return Some("ada") }
if id == 2 { return Some("grace") }
None
}
fn main() {
print(findUser(1))
print(findUser(9))
match findUser(2) {
Some(name) => print("found {name}")
None => print("no such user")
}
} Some("ada")
None
found grace An Option<string> is not a string. You can't use it as one by accident, which is the
mistake null lets you make:
tin check no-null.tinfn findUser(id: int): Option<string> {
if id == 1 { return Some("ada") }
None
}
fn main() {
let name = findUser(1)
print(name.upper())
} error: no method 'upper' for Option<string>
--> no-null.tin:8:9
|
8 | print(name.upper())
| ^^^^^^^^^^
= note: x.f(y) is sugar for f(x, y): any function whose first parameter fits can be called as a method When there is an obvious default, or gives you the value or the fallback. The standard
parseInt returns an Option, because not every string is a number:
tin run or.tinfn main() {
let port = parseInt("8080") // parseInt returns an Option<int>
let bad = parseInt("eighty")
print(port)
print(bad)
print(port.or(80)) // the value, or a fallback
print(bad.or(80))
print(bad.isNone())
} Some(8080)
None
8080
80
true Success or failure: Result
When something can fail and the caller should know why, return Result<T, E>:
Ok(value) or Err(error).
tin run result.tin// Result<T, E> is Ok(value) or Err(error): an operation that can fail, and why.
fn divide(a: int, b: int): Result<int, string> {
if b == 0 { return Err("cannot divide {a} by zero") }
Ok(a / b)
}
fn main() {
print(divide(10, 2))
print(divide(1, 0))
match divide(7, 0) {
Ok(n) => print("result: {n}")
Err(why) => print("failed: {why}")
}
} Ok(5)
Err("cannot divide 1 by zero")
failed: cannot divide 7 by zero Passing a failure up with ?
Often a function can't do anything useful about a failure, except pass it on to its caller. Writing a
match for that each time gets tedious, so Tin has ?. Put it after a
Result: on Ok you get the value, and on Err the function returns that
error right away.
tin run question.tinfn 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")
}
}
// ? takes the Ok value out, or returns the Err from this function right away.
fn address(host: string, port: string): Result<string, string> {
let p = parsePort(port)?
Ok("{host}:{p}")
}
fn main() {
print(address("localhost", "8080"))
print(address("localhost", "http"))
print(address("localhost", "99999"))
} Ok("localhost:8080")
Err("'http' is not a number")
Err("port 99999 is out of range") ? works the same way on an Option, in a function that returns an
Option:
tin run question-option.tin// ? works on Option too, in a function that returns an Option.
fn sumOf(a: string, b: string): Option<int> {
let x = parseInt(a)?
let y = parseInt(b)?
Some(x + y)
}
fn main() {
print(sumOf("2", "40"))
print(sumOf("2", "forty"))
} Some(42)
None Your own error types
A string explains a failure to a person. A sum type lets the code tell failures apart, and lets each case carry details:
tin run own-error.tin// The error can be your own sum type, so callers can tell the failures apart.
type WithdrawError = | Insufficient { short: int } | Negative
fn withdraw(balance: int, amount: int): Result<int, WithdrawError> {
if amount < 0 { return Err(Negative) }
if amount > balance { return Err(Insufficient { short: amount - balance }) }
Ok(balance - amount)
}
fn explain(e: WithdrawError): string => match e {
Insufficient { short } => "not enough: {short} short"
Negative => "amount can't be negative"
}
fn main() {
for amount in [30, 500, -5] {
match withdraw(100, amount) {
Ok(left) => print("ok, {left} left")
Err(e) => print(explain(e))
}
}
} ok, 70 left
not enough: 400 short
amount can't be negative When to panic
A panic stops the program. Tin panics on things that are bugs, not on things that can happen in normal use: reading past the end of an array, integer overflow, dividing by zero.
tin run panic.tin// panic is for bugs: things that should never happen. It stops the program.
fn main() {
let scores = [90, 72, 85]
print(scores[0])
print(scores[3]) // there is no fourth score
} 90
panic: index 3 is out of bounds for an array of length 3 A rule of thumb: if the caller could reasonably handle it (a missing file, a bad number from a
user, a model that answered nonsense), return a Result. If it means your program is wrong,
let it panic.
Tasks
●○○ Task 1: Safe division
Write safeDivide(a: float, b: float): Option<float> that returns None when
b is zero. Print it for 1/4 and 1/0, then 9/0 with a fallback of 0.0.
Solution
tin run task-1.solution.tinfn safeDivide(a: float, b: float): Option<float> {
if b == 0.0 { return None }
Some(a / b)
}
fn main() {
print(safeDivide(1.0, 4.0))
print(safeDivide(1.0, 0.0))
print(safeDivide(9.0, 0.0).or(0.0))
} Some(0.25)
None
0.0 ●●○ Task 2: Read a setting
Parse lines like volume=7 into Setting { key: string, value: int }. Return
Err with a helpful message when there is no = or the value isn't a number.
Hint: line.split("=") gives you an array of the parts, and parts.len how many
there are.
Solution
tin run task-2.solution.tintype Setting = { key: string, value: int }
// "key=value", for example "volume=7"
fn parseSetting(line: string): Result<Setting, string> {
let parts = line.split("=")
if parts.len != 2 { return Err("expected key=value, got '{line}'") }
match parseInt(parts[1]) {
Some(n) => Ok(Setting { key: parts[0], value: n })
None => Err("'{parts[1]}' is not a number")
}
}
fn main() {
print(parseSetting("volume=7"))
print(parseSetting("volume"))
print(parseSetting("volume=loud"))
} Ok(Setting { key: "volume", value: 7 })
Err("expected key=value, got 'volume'")
Err("'loud' is not a number") ●●○ Task 3: Two numbers or nothing
Write parsePoint(x: string, y: string): Result<(int, int), string> using a helper that
turns parseInt's Option into a Result, and ? twice.
Solution
tin run task-3.solution.tinfn parsePoint(x: string, y: string): Result<(int, int), string> {
let a = parseNumber(x)?
let b = parseNumber(y)?
Ok((a, b))
}
fn parseNumber(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => Ok(n)
None => Err("'{text}' is not a number")
}
}
fn main() {
print(parsePoint("3", "4"))
print(parsePoint("3", "four"))
} Ok((3, 4))
Err("'four' is not a number") What's next
Next: Arrays and maps. Lists of values, lookups by key, and the methods you use every day.
In the reference: Option, Result and ? · Option and Result functions