blob: 7bebf11e4545daaf35fc7bf6c3ec1be714a7de16 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
fn foo() string {
println('foo()')
return 'foo'
}
fn foo2() string {
println('start')
defer {
println('defer')
}
defer {
println('defer2')
}
println('end')
return foo()
}
fn test_defer() {
assert foo2() == 'foo'
}
fn set_num(i int, mut n Num) {
defer {
println('exiting')
n.val++
}
println('Hi')
if i < 5 {
return
} else {
n.val++
}
}
fn set_num_opt(mut n Num) ?int {
defer {
n.val = 1
}
return 99
}
struct Num {
mut:
val int
}
fn (n Num) add(i int) int {
return n.val + i
}
fn test_defer_early_exit() {
mut sum := Num{0}
for i in 0 .. 10 {
set_num(i, mut sum)
}
println('sum: $sum.val')
assert sum.val == 15
}
fn test_defer_option() {
mut ok := Num{0}
set_num_opt(mut ok) or {}
assert ok.val == 1
}
fn test_defer_with_anon_fn() {
mut f := &Num{
val: 110
}
defer {
assert f.add(1) == 111
}
go fn () {
defer {
println('deferred 1')
}
}()
x := fn () {
defer {
println('defered 2')
}
return
}
x()
return
}
fn set_num_if(mut n Num, v int, cond bool) {
if cond {
defer {
n.val = v
}
}
}
fn test_defer_with_if() {
mut n := Num{0}
set_num_if(mut n, 10, true)
assert n.val == 10
set_num_if(mut n, 20, false)
assert n.val == 10
}
fn test_defer_order() {
mut i := 0
defer {
i++
assert i == 3
}
defer {
i++
assert i == 2
}
defer {
i++
assert i == 1
}
}
fn test_defer_access() {
if true {
mut i := 0
defer {
i++
assert i == 1
}
}
}
fn test_defer_arrays() {
mut ia := []int{}
defer {
ia << 1
}
}
fn test_defer_str_interpol() {
mut t := []string{}
defer {
t << 'test'
t << '${t[0]}'
}
}
fn test_defer_not_change_return_values() {
assert num() == 10
}
fn num() int {
mut ret := 10
defer {
ret = 20
}
return ret
}
|