v2 / vlib / v / tests / interfaces / interface_closure_test.v
88 lines · 70 sloc · 1.31 KB · 04097e99df51d4edb08d61db9e3ceeff6943a9e9
Raw
1interface ITest {
2mut:
3 caller(a Test) !
4}
5
6struct Test {
7}
8
9struct Test2 {
10}
11
12fn (t2 Test2) with_reader(func fn (a Test) !) ! {
13 return func(Test{})
14}
15
16fn (t Test) caller(a Test) ! {
17 println('ok')
18}
19
20fn get() ITest {
21 return Test{}
22}
23
24fn test_main() {
25 mut a := get()
26
27 b := Test2{}
28 b.with_reader(a.caller)!
29 assert true
30}
31
32interface ClosureCommand {
33 value() int
34mut:
35 increment()
36}
37
38struct MutableClosureCommand {
39mut:
40 value_ int
41}
42
43fn (cmd MutableClosureCommand) value() int {
44 return cmd.value_
45}
46
47fn (mut cmd MutableClosureCommand) increment() {
48 cmd.value_++
49}
50
51fn with_closure_connection(func fn () !) ! {
52 func()!
53}
54
55fn with_closure_writer(func fn () !) ! {
56 func()!
57}
58
59fn with_closure_reader(func fn () !) ! {
60 func()!
61}
62
63fn write_closure_command(cmd ClosureCommand) ! {
64 assert cmd.value() == 41
65}
66
67fn read_closure_command(mut cmd ClosureCommand) ! {
68 cmd.increment()
69}
70
71fn process_closure_command(mut cmd ClosureCommand) ! {
72 with_closure_connection(fn [mut cmd] () ! {
73 with_closure_writer(fn [cmd] () ! {
74 write_closure_command(cmd)!
75 })!
76 with_closure_reader(fn [mut cmd] () ! {
77 read_closure_command(mut cmd)!
78 })!
79 })!
80}
81
82fn test_nested_closure_captures_mut_interface_by_value() {
83 mut cmd := ClosureCommand(MutableClosureCommand{
84 value_: 41
85 })
86 process_closure_command(mut cmd)!
87 assert cmd.value() == 42
88}
89