← All examples

Owning function

A function that captured with copy or give carries what it captured, so it is owned like a list: copying or handing it on takes a word.

owning_function.zg
# A function that captured with `copy` or `give` carries what it captured, so it is owned
# like a list: copying or handing it on takes a word (owner, 2026-09-24: a). A function
# carrying nothing, or only lends, copies by itself like a number.
MAIN {
    let 'xs' := [1, 2, 3];
    let 'count' := fn [] -> uint64 with [copy 'xs'] { return list.length[lend 'xs']; };
    let 'again' := copy 'count';        # its own copy of the list inside
    let 'moved' := give 'count';        # 'count' is gone after this
    let 'inc' := fn ['a': int32] -> int32 { return 'a' plus 1; };
    let 'inc2' := 'inc';                # carries nothing: no word needed
    std::print.useful['again'[], " ", 'moved'[], " ", 'inc2'[41], newln];
}
Output
3 3 42