Tour · 10 of 18
Absence and failure
The program on the right looks up an email and applies a coupon.
#Option
fn email_of(name: string) -> string?:
if name == "Ada": .Some("ada@example.com") else: .NoneOption[T] is either .Some(value) or .None, and T? is its short
spelling. The caller must handle both, here with unwrap_or.
#Result
fn discount(code: string) -> Result[i32, CouponError]:
if code == "SPRING10": .Ok(10) else: .Err(.Unknown(code))Result[T, E] is either .Ok(value) or .Err(error). Here the error is a
CouponError.
#?
percent := discount(code)?Postfix ? takes the success value. On failure, it returns the same
error from the current function. So the success path stays straight.
#Matching a result
match checkout(5000, "SPRING10"):
.Ok(due) => println("due: $due")
.Err(.Unknown(code)) => println("unknown coupon: $code")match handles each case. A pattern can reach inside the error, as
.Err(.Unknown(code)) does.
Run it. Grace has no email, and the coupon takes 10% off 5000. So it
prints no email and due: 4500.
Try it: change percent := discount(code)? to percent := discount(code) and press Run.
Run: Ctrl+Enter · Pages: Alt+← Alt+→