DEV Community

flisk
flisk

Posted on

Goose: Push into an Array, Pass It to a Function

Part 3 of Goose, then any language on Flisk. This is the program part 4 will compile into an image. The function is the one from part 2.

shop.goose:

fn total(xs: i64[:]) -> i64 {
    var t = 0;
    for x in xs { t += x; }
    return t;
}

fn main() {
    var grow: i64[>..] = [];
    for i in 5 { grow.push(i * i); }
    print(grow);
    print(total(grow));
    print(total(grow[1..4]));
}
Enter fullscreen mode Exit fullscreen mode
goose shop.goose
Enter fullscreen mode Exit fullscreen mode

for i in 5 is 0, 1, 2, 3, 4. push appends. i64[>..] is grow-only: references into it stay valid across push. That is the array you want until you have a reason to pick another spelling.

grow[1..4] is a slice, exclusive at the end. total accepts the whole array and the slice, because both become i64[:]. grow[^2..] is the last two elements. ^k means len - k.

What not to copy by accident

var a: i64[>..] =;[1][2][3]
var b = a;       // b names the same array
var c = copy(a); // this one is a copy
Enter fullscreen mode Exit fullscreen mode

Fixed-size values copy on assignment. A growable array does not. f(grow) also does not copy the elements.

let versus var still applies inside total. t is var because t += x reassigns it.

Build it before Flisk sees it

goose build -o ./shop shop.goose
./shop
Enter fullscreen mode Exit fullscreen mode

The process prints and exits. That is a correct Goose program. It is not yet a Flisk service. Part 4 wraps a long-running process around this function, because BYO runs any language whose container stays up and answers /health. The function does not change.

Top comments (0)