Variadics and slice spread
A rest parameter is a slice inside the function and a Go variadic at its call boundary.
Source
ts
import go fmt from "fmt";
function sum(prefix: int, ...values: int[]): int {
let total = prefix;
for (const value of values) { total += value; }
return total;
}
function last<T>(fallback: T, ...values: T[]): T {
if (len(values) === 0) { return fallback; }
return values[len(values) - 1];
}
function main(): void {
const values = [3, 4, 5];
fmt.Println(sum(10), sum(10, 1, 2), sum(10, values...));
fmt.Println(last("empty"), last("empty", "hello", "planet"));
}Run
sh
keika check variadics.km
keika run variadics.kmExpected output:
text
10 13 22
empty planetCall rules
- A rest parameter uses
...values: T[]and must be last. - Callers may pass zero or more individual
Tvalues. - One final
T[]may be expanded withvalues.... - Fixed arguments still appear before the expanded slice.
- Generic inference includes both individual and expanded arguments.
The same form works for functions, methods, interfaces, arrows, function types, and constructors. A plain T[] parameter is not interchangeable with a variadic signature.
The documentation suite also rejects spreading string[] into ...values: int[], verifying that spread does not bypass element typing.