v2 / vlib / v / tests / closure_with_fn_ref_var_test.v
40 lines · 32 sloc · 713 bytes · 8a39f8c5ce74db08c1b6129cb5e543abaace71b8
Raw
1module main
2
3fn f_a() int {
4 println('a')
5 return 1
6}
7
8fn test_closure_with_fn_ref_var() {
9 f := f_a
10 ref := &f
11 println('ref=0x${ptr_str(ref)}')
12
13 handler := fn [ref] () int { // ref_fn is captured as a direct function pointer (*fn) instead of a pointer to a function (**fn)
14 println('in closure: ref=0x${ptr_str(ref)}')
15 deref_fn := *ref
16 println('in closure: deref=0x${ptr_str(deref_fn)}')
17 return deref_fn()
18 }
19
20 f()
21 deref := *ref
22 println('deref=0x${ptr_str(deref)}')
23 assert deref() == 1
24 assert handler() == 1
25}
26
27type Fun = fn () int
28
29fn test_closure_with_fn_ref_var_option() {
30 opt := ?Fun(f_a)
31
32 handler := fn [opt] () int {
33 if g := opt {
34 return g()
35 }
36 return 0
37 }
38
39 assert handler() == 1
40}
41