Generic functions and structs
This recipe combines a generic nominal value type with a generic function.
Project tree
text
generics/
└── main.kmSource
ts
import go fmt from "fmt";
struct Box<T> {
public value: T;
public function get(): T {
return this.value;
}
}
function choose<T>(first: T, second: T, useSecond: boolean): T {
if (useSecond) { return second; }
return first;
}
function main(): void {
const box: Box<string> = Box<string> { value: "hello" };
const selected = choose<int>(21, 42, true);
fmt.Println(box.get(), selected);
}Run
sh
keika check main.km
keika run main.kmExpected output:
text
hello 42Contract demonstrated
Box<string>is explicitly instantiated in the type and literal.- The value receiver method substitutes
Twithstring. choose<int>supplies an explicit function argument;choose(21, 42, true)could inferintinstead.- Different instantiations such as
Box<string>andBox<int>are distinct types. - A generic struct remains a value: assignment copies the outer Go struct.
Use T extends comparable when equality or map-key use requires the constraint. Native type sets, imported Go constraints, generic aliases and method-local type parameters are also supported; see the guide for their rules and examples.