2019-07-21 01:49:34 +03:00
|
|
|
fn foo() string {
|
2019-10-12 22:01:50 +03:00
|
|
|
println('foo()')
|
|
|
|
return 'foo'
|
|
|
|
}
|
2019-07-21 01:49:34 +03:00
|
|
|
|
2019-10-12 22:01:50 +03:00
|
|
|
fn foo2() string {
|
|
|
|
println('start')
|
2020-03-27 13:21:00 +03:00
|
|
|
defer {
|
|
|
|
println('defer')
|
|
|
|
}
|
|
|
|
defer {
|
|
|
|
println('defer2')
|
|
|
|
}
|
2019-10-12 22:01:50 +03:00
|
|
|
println('end')
|
|
|
|
return foo()
|
|
|
|
}
|
2019-07-21 01:49:34 +03:00
|
|
|
|
2019-10-12 22:01:50 +03:00
|
|
|
fn test_defer() {
|
|
|
|
assert foo2() == 'foo'
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_num(i int, n mut Num) {
|
2020-03-27 13:21:00 +03:00
|
|
|
defer {
|
|
|
|
println('exiting')
|
|
|
|
n.val++
|
|
|
|
}
|
|
|
|
println('Hi')
|
2019-10-12 22:01:50 +03:00
|
|
|
if i < 5 {
|
|
|
|
return
|
2020-03-27 13:21:00 +03:00
|
|
|
}
|
|
|
|
else {
|
2019-12-08 15:30:14 +03:00
|
|
|
n.val++
|
2019-10-12 22:01:50 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_num_opt(n mut Num) ?int {
|
2020-03-27 13:21:00 +03:00
|
|
|
defer {
|
|
|
|
n.val = 1
|
|
|
|
}
|
2019-10-12 22:01:50 +03:00
|
|
|
return 99
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Num {
|
|
|
|
mut:
|
|
|
|
val int
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_defer_early_exit() {
|
2020-03-27 13:21:00 +03:00
|
|
|
mut sum := Num{
|
|
|
|
0}
|
|
|
|
for i in 0 .. 10 {
|
2019-10-12 22:01:50 +03:00
|
|
|
set_num(i, mut sum)
|
|
|
|
}
|
2020-03-27 13:21:00 +03:00
|
|
|
println('sum: $sum.val')
|
2019-10-12 22:01:50 +03:00
|
|
|
assert sum.val == 15
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_defer_option() {
|
2020-03-27 13:21:00 +03:00
|
|
|
mut ok := Num{
|
|
|
|
0}
|
2019-11-04 02:38:49 +03:00
|
|
|
set_num_opt(mut ok) or {
|
|
|
|
assert false
|
|
|
|
}
|
2019-10-12 22:01:50 +03:00
|
|
|
assert ok.val == 1
|
|
|
|
}
|