| 1 | struct Foo {} |
| 2 | |
| 3 | fn (f Foo) foo() string { |
| 4 | return 'foo' |
| 5 | } |
| 6 | |
| 7 | fn (f Foo) bar() string { |
| 8 | return 'bar' |
| 9 | } |
| 10 | |
| 11 | struct NamedFoo { |
| 12 | name string |
| 13 | } |
| 14 | |
| 15 | fn (f NamedFoo) foo() string { |
| 16 | return 'foo ${f.name}' |
| 17 | } |
| 18 | |
| 19 | fn (f NamedFoo) bar() string { |
| 20 | return 'bar ${f.name}' |
| 21 | } |
| 22 | |
| 23 | fn test_main() { |
| 24 | f := Foo{} |
| 25 | mut results := []string{} |
| 26 | $for method in Foo.methods { |
| 27 | x := fn [method, f] () string { |
| 28 | return f.$method() |
| 29 | } |
| 30 | results << x() |
| 31 | } |
| 32 | assert results[0] == 'foo' |
| 33 | assert results[1] == 'bar' |
| 34 | } |
| 35 | |
| 36 | fn test_comptime_method_value() { |
| 37 | f := NamedFoo{'rabbit'} |
| 38 | mut results := []string{} |
| 39 | $for method in NamedFoo.methods { |
| 40 | x := f.$(method) |
| 41 | results << x() |
| 42 | } |
| 43 | assert results[0] == 'foo rabbit' |
| 44 | assert results[1] == 'bar rabbit' |
| 45 | } |
| 46 | |
| 47 | @[heap] |
| 48 | struct MethodMapApp { |
| 49 | prefix string |
| 50 | } |
| 51 | |
| 52 | fn (app &MethodMapApp) alpha() string { |
| 53 | return '${app.prefix}:alpha' |
| 54 | } |
| 55 | |
| 56 | fn (app &MethodMapApp) beta() string { |
| 57 | return '${app.prefix}:beta' |
| 58 | } |
| 59 | |
| 60 | fn build_method_map[T](app &T) map[string]fn () string { |
| 61 | mut syms := map[string]fn () string{} |
| 62 | $for method in T.methods { |
| 63 | syms[method.name] = app.$(method.name) |
| 64 | } |
| 65 | return syms |
| 66 | } |
| 67 | |
| 68 | fn test_comptime_method_value_map() { |
| 69 | app := MethodMapApp{'ctx'} |
| 70 | syms := build_method_map(app) |
| 71 | assert syms['alpha']() == 'ctx:alpha' |
| 72 | assert syms['beta']() == 'ctx:beta' |
| 73 | } |
| 74 | |