generics

関数の型パラメータは fn identity <.T: Copy> のように宣言し、型式の中では .T のように参照します。Option .TResult .T .E のような標準型も generic な型です。

TESTstdionormalize_newlines
#entry main
#indent 4
#target std

#import "core/option" as *
#import "core/result" as *
#import "core/traits/copy" as *
#import "std/test" as *

fn identity <.T: Copy> %fn .T .T \x:
    x

fn main %impure fn void i32 \void:
    let maybe %Option i32 identity some 7
    let answer %Result i32 str identity ok 1
    let checks:
        checks_new
        |> checks_push assert_eq_i32 42 identity 42
        |> checks_push assert identity true
        |> checks_push assert is_some maybe
        |> checks_push assert is_ok answer
    let shown checks_print_report checks
    checks_exit_code shown

この例では Copy bound を付け、i32boolOption i32Result i32 str のような copy できる値だけを受け取ります。所有権を持つ値まで generic に扱う場合は、move / borrow / Clone の境界を別に設計します。

On this page