Out parameter
A function returns one value. Sometimes you want two things back: the answer, and whether the answer is any good. One long-standing way to get both is the out-parameter — the caller hands over its own variable, the function writes the answer into it, and the return value is left free to say something else.
You will meet out-parameters in older code, in the standard library and in C libraries, so it pays to read them fluently. This lesson also shows their weak spots, and why returning an optional T? is usually the better choice for code you write yourself.
The shape of an out-parameter
In Rux the place to write into is a &var T parameter, the writable borrow from Mutable reference. The answer travels through result, and the bool that comes back says whether to trust it:
func PercentOf(part: int, whole: int, result: &var int) -> bool {
if whole == 0 {
return false;
}
result = part * 100 / whole;
return true;
}
Assigning to result lands in the caller's storage. The caller prepares a variable first and passes it by name:
var share: int = 0;
if PercentOf(3, 4, share) {
PrintLine("3 of 4 is {}%", share);
}
flowchart LR
main["`Main`<br/>`var share = 0`"] -- "`share`, borrowed `&var`" --> f["`PercentOf(3, 4, result)`"]
f -- "`result = 75`" --> share[("`share`")]
f -- "returns `true`" --> check{"`if`"}
check --> print["print `share`"]The variable must be a var, because the function writes into it, and it must already hold a value, because the borrow is made before the function decides whether to write.
The flag nobody has to read
Here is the weak spot. Nothing forces the caller to look at the bool:
PercentOf(1, 0, share);
PrintLine("1 of 0, flag ignored: {}%", share);
The whole is zero, so PercentOf returns false and writes nothing. The flag is dropped, and share still holds 75 from the call before. The program prints a confident 75% for a question that has no answer, and the compiler has no reason to object.
Reading someone else's flag
The standard library uses out-parameters too, and where an API is shaped for C the place is a raw pointer, *var T, rather than a borrow. ConvertChecked writes the converted value through a *var int8, so the caller passes the address with @, and returns a bool:
var narrowed: int8 = 0;
let lost = ConvertChecked<int, int8>(300, @narrowed);
The caller only takes an address, which is safe. The function writes through it, inside its own unsafe block, and it is the function's documentation that promises the write is sound.
| Function | true means |
|---|---|
PercentOf | the answer is good |
ConvertChecked | something was lost — the answer is not exact |
The two read in opposite directions. With a bare bool, only the documentation tells you which way round it is. Here 300 does not fit in an int8, so lost is true and narrowed holds the wrapped value 44.
The optional alternative
The same question with an optional answer puts the answer and its absence together in the return value:
func Percent(part: int, whole: int) -> int? {
if whole == 0 {
return none;
}
return part * 100 / whole;
}
let good = Percent(3, 4) ?? -1;
let bad = Percent(1, 0) ?? -1;
An int? is not an int. It cannot be printed as a number or added to one until ??, match or if … is .Some(…) has dealt with none, so there is no stale value to misuse.
| Out-parameter | Optional T? | |
|---|---|---|
| Where the answer goes | a variable the caller prepared first | the return value |
| How "no answer" is reported | a bool, read whichever way it reads | none, in the same value |
| A caller that ignores it | compiles, and keeps a stale value | cannot use the answer as a plain T |
| An answer when there is none | whatever the variable held before | none — there is nothing to misuse |
When the caller also needs to know why there is no answer, declare -> T throws E instead, as in Fallible. For new code, prefer either. Reach for an out-parameter when an existing API asks for one.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// An out-parameter is a place the caller hands over so a function can write its answer into the
// caller's own variable. In Rux that place is a `&var T` parameter: the caller passes `share`,
// and the function assigns `result = ...`, which lands in the caller's storage. The return value
// is then free to say something else, usually whether the answer is good.
//
// Older code and some of the standard library work this way, so it is worth reading fluently.
// Where the answer crosses into C, the place is a raw `*var T` instead, the caller passes
// `@share`, and writing through it needs `unsafe`. But either form has two weak spots. The caller
// must have a variable ready before the call, and nothing forces anyone to look at the flag:
// ignore it, and the variable quietly keeps a stale value.
//
// Returning an optional `T?` closes both gaps. The answer only exists when there is one, and it
// cannot be used until `??`, `match` or `if ... is .Some(...)` has dealt with `none`. When the
// caller also needs to know why there is no answer, declare `-> T throws E` instead. For new code,
// prefer either; reach for an out-parameter when an existing API asks for one.
import Core::ConvertChecked;
import Io::PrintLine;
// Out-parameter style: the answer goes through `result`, and the `bool` says whether to trust it.
func PercentOf(part: int, whole: int, result: &var int) -> bool {
if whole == 0 {
return false;
}
result = part * 100 / whole;
return true;
}
// The same question with an optional answer. The answer and its absence travel together.
func Percent(part: int, whole: int) -> int? {
if whole == 0 {
return none;
}
return part * 100 / whole;
}
func Main() -> int {
var share: int = 0;
if PercentOf(3, 4, share) {
PrintLine("3 of 4 is {}%", share);
}
// The mistake the compiler cannot see: the flag is dropped, nothing was written, and `share`
// still says 75 from the call before.
PercentOf(1, 0, share);
PrintLine("1 of 0, flag ignored: {}%", share);
// The standard library uses out-parameters too. `ConvertChecked` writes the converted value
// through a `*var int8` and returns `true` when something was lost, which is the opposite of
// `PercentOf` above. With a bare `bool`, only the documentation tells you which way round it
// reads.
var narrowed: int8 = 0;
let lost = ConvertChecked<int, int8>(300, @narrowed);
PrintLine("300 into int8: lost {}, wrote {}", lost, narrowed);
// The optional needs no variable prepared in advance, and its value cannot be used as an
// `int` until the absence has been dealt with, here by `??`.
let good = Percent(3, 4) ?? -1;
let bad = Percent(1, 0) ?? -1;
PrintLine("optional: {}% and {}%", good, bad);
return 0;
}
Besides Io, its Rux.toml lists Core under [Dependencies].
Run it
cd Examples/Memory/OutParameter
rux run
3 of 4 is 75%
1 of 0, flag ignored: 75%
300 into int8: lost true, wrote 44
optional: 75% and -1%
Common mistakes
Try it yourself
- Write
func Divide(a: int, b: int, quotient: &var int, remainder: &var int) -> boolthat hands back two answers at once, and call it with twovarvariables. - Change
PercentOfto write0intoresultbefore it returnsfalse. Does that cure the stale75%? What does the caller still not know? - Convert 100 into an
int8withConvertCheckedand check thatlostisfalse. - Rewrite
PercenttothrowaZeroWholeerror instead of returningnone, and handle it withtry Percent(1, 0) catch { _ => -1 }.
Learn more
- Optional and Coalesce — the alternative this lesson recommends
- Fallible — when the caller needs to know why
- Checked convert —
ConvertCheckedand its relatives in full - Pointer types in the Rux Reference