1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: execute defer block *after* return expression is evaluated (#9893)

This commit is contained in:
Uwe Krüger
2021-04-27 00:42:16 +02:00
committed by GitHub
parent 4eb8072882
commit 787a63dab6
5 changed files with 273 additions and 118 deletions

View File

@@ -1383,6 +1383,48 @@ fn read_log() {
}
```
If the function returns a value the `defer` block is executed *after* the return
expression is evaluated:
```v
import os
enum State {
normal
write_log
return_error
}
// write log file and return number of bytes written
fn write_log(s State) ?int {
mut f := os.create('log.txt') ?
defer {
f.close()
}
if s == .write_log {
// `f.close()` will be called after `f.write()` has been
// executed, but before `write_log()` finally returns the
// number of bytes written to `main()`
return f.writeln('This is a log file')
} else if s == .return_error {
// the file will be closed after the `error()` function
// has returned - so the error message will still report
// it as open
return error('nothing written; file open: $f.is_opened')
}
// the file will be closed here, too
return 0
}
fn main() {
n := write_log(.return_error) or {
println('Error: $err')
0
}
println('$n bytes written')
}
```
## Structs
```v