v0.4.0
Memory · Lesson 15.2

Out parameter

Source
Return an answer through a &var T out-parameter, and see why returning an optional T? is usually the better choice.

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.

Functiontrue means
PercentOfthe answer is good
ConvertCheckedsomething 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-parameterOptional T?
Where the answer goesa variable the caller prepared firstthe return value
How "no answer" is reporteda bool, read whichever way it readsnone, in the same value
A caller that ignores itcompiles, and keeps a stale valuecannot use the answer as a plain T
An answer when there is nonewhatever the variable held beforenone — 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.

Src/Main.rux
// 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

  1. Write func Divide(a: int, b: int, quotient: &var int, remainder: &var int) -> bool that hands back two answers at once, and call it with two var variables.
  2. Change PercentOf to write 0 into result before it returns false. Does that cure the stale 75%? What does the caller still not know?
  3. Convert 100 into an int8 with ConvertChecked and check that lost is false.
  4. Rewrite Percent to throw a ZeroWhole error instead of returning none, and handle it with try Percent(1, 0) catch { _ => -1 }.

Learn more