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:
42
doc/docs.md
42
doc/docs.md
@@ -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
|
||||
|
Reference in New Issue
Block a user