Skip to content

Generic functions and structs ​

This recipe combines a generic nominal value type with a generic function.

Project tree ​

text
generics/
└── main.km

Source ​

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.km

Expected output:

text
hello 42

Contract demonstrated ​

  • Box<string> is explicitly instantiated in the type and literal.
  • The value receiver method substitutes T with string.
  • choose<int> supplies an explicit function argument; choose(21, 42, true) could infer int instead.
  • Different instantiations such as Box<string> and Box<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.

See Functions and generics.

Kinmokusei is a pre-1.0 project. Documentation describes implemented behavior.