v2 / vlib / v / tests / fns / anon_fn_test.v
78 lines · 64 sloc · 1.38 KB · 8d0709ce1640b2179145dc578c670639bc4c34d2
Raw
1import sync
2
3fn test_go_anon_fn() {
4 mut wg := sync.new_waitgroup()
5 wg.add(1)
6 spawn fn (mut wg sync.WaitGroup) {
7 wg.done()
8 }(mut wg)
9 wg.wait()
10}
11
12struct AnonFnWrapper {
13mut:
14 fn_ fn () bool
15}
16
17fn test_anon_assign_struct() {
18 mut w := AnonFnWrapper{}
19 w.fn_ = fn () bool {
20 return true
21 }
22 assert w.fn_()
23}
24
25//
26
27fn fnormal(mut acc []string, e int) []string {
28 acc << e.str()
29 return acc
30}
31
32fn test_anon_fn_returning_a_mut_parameter_should_act_the_same_as_normal_fn_returning_a_mut_parameter() {
33 fanon := fn (mut acc []string, e int) []string {
34 acc << e.str()
35 return acc
36 }
37 assert '${fanon}' == '${fnormal}'
38 mut a := ['a', 'b', 'c']
39 mut b := a.clone()
40 x := fanon(mut a, 123)
41 y := fnormal(mut b, 123)
42 assert a == b
43}
44
45// for issue 20163
46struct Struct {}
47
48fn test_spawn_anon_fn_with_closure_parameters_and_mut_ref_parameters() {
49 mut s := &Struct{}
50 a := 1
51
52 t := spawn fn [a] (mut s Struct) int {
53 return a
54 }(mut s)
55 assert t.wait() == 1
56}
57
58struct CallbackEvent {}
59
60fn call_event_handler(cb fn (CallbackEvent) bool) bool {
61 return cb(CallbackEvent{})
62}
63
64fn call_two_arg_handler(cb fn (CallbackEvent, int) int) int {
65 return cb(CallbackEvent{}, 7)
66}
67
68fn test_anon_fn_can_omit_all_unused_callback_params() {
69 assert call_event_handler(fn () bool {
70 return true
71 })
72}
73
74fn test_anon_fn_can_omit_trailing_callback_params() {
75 assert call_two_arg_handler(fn (_ CallbackEvent) int {
76 return 42
77 }) == 42
78}
79