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 writenone. - Opening an optional with
matchand the presence patternsvalue?andnone. - Replacing absence with a fallback using
??, which runs the fallback only when it is needed. - Leaving a function or loop with
?? return,?? continueor?? 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… | Use | Lesson |
|---|---|---|
| run different code for each case | match with value? / none | Presence |
| carry on with a stand-in value | ?? fallback | Coalesce |
| stop this function or loop | ?? return, ?? continue, ?? break | Coalesce exit |
| let the caller decide | postfix ? | Optional propagate |
Lessons
| Lesson | What you will learn | |
|---|---|---|
| 8.1 | Optional | a value that may be missing: int? and none |
| 8.2 | Presence | match an optional with value? and none arms |
| 8.3 | Coalesce | supply a fallback for a missing value with ?? |
| 8.4 | Coalesce exit | leave with ?? return, ?? continue or ?? break when a value is missing |
| 8.5 | Optional propagate | pass absence to the caller with ? |
| 8.6 | Nested optional | int??: 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.