Part 8: Optionals

Some questions have no answer: the first even number in a list of odd ones, the score of a player nobody signed. Rux writes "a value that may be absent" as T? — an int? holds an int or none — and the compiler will not let you use it as an int until you have said what happens when it is missing. This part covers every tool for saying so, from a full match to a single character.

What you will learn

  • What int? is, how a plain value becomes a present optional, and how to write none.
  • Opening an optional with match and the presence patterns value? and none.
  • Replacing absence with a fallback using ??, which runs the fallback only when it is needed.
  • Leaving a function or loop with ?? return, ?? continue or ?? break.
  • Passing absence on to the caller with a postfix ?.
  • Telling "nothing found" from "found nothing" with int??.

What to do with an optional

Every lesson after the first answers one question — what should happen when the value is none?

flowchart LR
    o(["An int?"]) --> m["match<br/>value? => …<br/>none => …"]
    o --> c["?? fallback"]
    o --> x["?? return / continue / break"]
    o --> p["? (postfix)"]
    m --> m2["Each case gets<br/>its own code"]
    c --> c2["A plain int:<br/>the value, or the fallback"]
    x --> x2["A plain int,<br/>or control leaves here"]
    p --> p2["A plain int,<br/>or the function<br/>returns none"]
You want to…UseLesson
run different code for each casematch with value? / nonePresence
carry on with a stand-in value?? fallbackCoalesce
stop this function or loop?? return, ?? continue, ?? breakCoalesce exit
let the caller decidepostfix ?Optional propagate

Lessons

LessonWhat you will learn
8.1Optionala value that may be missing: int? and none
8.2Presencematch an optional with value? and none arms
8.3Coalescesupply a fallback for a missing value with ??
8.4Coalesce exitleave with ?? return, ?? continue or ?? break when a value is missing
8.5Optional propagatepass absence to the caller with ?
8.6Nested optionalint??: telling "nothing found" from "found nothing"

Before you start

Finish Part 7: Patterns: an optional is opened with the same match, guards and exhaustiveness rules, and the first lesson assumes Variant and Variant match from Part 6. Each lesson's package is in the Examples repository's Optionals/ folder:

cd Examples/Optionals/Optional
rux run

After this part

An optional says only that a value is missing. Part 9: Errors adds the fallible T ! E, which also says why — with its own ?, its own fallbacks, and Absence to error to turn a none into a failure. After Part 9 you are ready for the checkpoint project Calculator.

For the patterns used here, see match in the Rux Reference.