v2 / vlib / v / tests / fns / methods_as_fields_test.v
119 lines · 99 sloc · 2.0 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1struct Foo {
2 s string
3mut:
4 i int
5}
6
7fn (f Foo) get_s() string {
8 return f.s
9}
10
11fn (f &Foo) get_s_ref() string {
12 return f.s
13}
14
15fn (f Foo) add(a int) int {
16 return a + f.i
17}
18
19fn (f &Foo) add_ref(a int) int {
20 return a + f.i
21}
22
23fn (mut f Foo) set(a int) {
24 f.i = a
25}
26
27fn (f_ Foo) set_val(a int) int {
28 mut f := unsafe { &f_ }
29 old := f.i
30 f.i = a
31 return old
32}
33
34fn test_methods_as_fields() {
35 mut f := Foo{
36 s: 'hello'
37 i: 1
38 }
39
40 get_s := f.get_s
41 get_s_ref := unsafe { f.get_s_ref }
42 add := f.add
43 add_ref := unsafe { f.add_ref }
44 set := unsafe { f.set }
45 set_val := f.set_val
46
47 assert typeof(get_s).str() == 'fn () string'
48 assert typeof(get_s_ref).str() == 'fn () string'
49 assert typeof(add).str() == 'fn (int) int'
50 assert typeof(add_ref).str() == 'fn (int) int'
51
52 assert get_s() == 'hello'
53 assert get_s_ref() == 'hello'
54 assert add(2) == 3
55 assert add_ref(2) == 3
56
57 assert f.i == 1
58 set(2)
59 assert f.i == 2
60 old := set_val(3)
61 assert f.i == 2
62 new := set_val(5)
63 assert old == new && old == 1
64}
65
66// the difference between these two tests is that here `f` is &Foo
67fn test_methods_as_fields_ref() {
68 mut f := &Foo{
69 s: 'hello'
70 i: 1
71 }
72
73 get_s := f.get_s
74 get_s_ref := unsafe { f.get_s_ref }
75 add := f.add
76 add_ref := unsafe { f.add_ref }
77 set := unsafe { f.set }
78 set_val := f.set_val
79
80 assert typeof(get_s).str() == 'fn () string'
81 assert typeof(get_s_ref).str() == 'fn () string'
82 assert typeof(add).str() == 'fn (int) int'
83 assert typeof(add_ref).str() == 'fn (int) int'
84
85 assert get_s() == 'hello'
86 assert get_s_ref() == 'hello'
87 assert add(2) == 3
88 assert add_ref(2) == 3
89
90 assert f.i == 1
91 set(2)
92 assert f.i == 2
93 old := set_val(3)
94 assert f.i == 2
95 new := set_val(5)
96 assert old == new && old == 1
97}
98
99struct GG_Ctx {
100 frame_fn fn (voidptr) int
101}
102
103@[heap]
104struct App {
105 msg string = 'hello'
106}
107
108fn (app &App) frame() int {
109 return app.msg.len
110}
111
112fn test_ctx_arg_expected() {
113 mut app := &App{}
114 mut ctx := &GG_Ctx{
115 frame_fn: app.frame
116 }
117 assert typeof(ctx.frame_fn).str() == 'fn (voidptr) int'
118 assert ctx.frame_fn(app) == 5
119}
120