XU XUv0.8.8
中文

Docs / Tutorial

09 · Generics, struct@, any

Bare any/temp is a dynamic box. fn f#T is monomorphised. struct@ Name is a method-set constraint; matching methods suffice — no impl.

Source

@main

struct@ ToString {
    fn to_string() string
}

struct User {
    name string
    age  int
}

fn (u User) to_string() string {
    << u.name
}

struct Score {
    n int
}

fn (s Score) to_string() string {
    << "score"
}

fn print_item(item# ToString) {
    println(item.to_string())
}

fn identity#T(x T) T {
    << x
}

fn main() int {
    u := User{name: "ada", age: 36}
    print_item(u)
    print_item(Score{n: 3})

    println(identity(42))

    let box: temp = 7
    println(box is int)
    v := box as int
    println(v)
    << 0
}

Build (from the language repo root; swap the binary for your platform):

xu run examples/09_generics_temp/main.xu
# or: xu build examples/09_generics_temp/main.xu
# default artifact is ./main on mac/linux, ./main.exe on Windows

Run from the separate examples repository root; source files live under examples/.