3 ms·
You can easily access and modify the named return variables from a deferred function body. If you had a variable declared in a block just before return, then y
by dullgiulio 9y ago
You can easily access and modify the named return variables from a deferred function body.
If you had a variable declared in a block just before return, then you return it, you have no way to modify it in defer.
I personally don't like this style of code, but I can see some uses.
- 19eightyfour 9y agoOk now I got they are in scope. About defer, could you think of it like defer makes a function into a function with multiple entry and exit points, possible to be stopped and resumed, like a coroutine?
- dullgiulio 9y agoEhm, not sure I understood, but I'd say no. Defer is just code that is executed in reverse order upon return from a fuction. It has nothing to do with coroutines. It's a cleaner way to write the usual C syntax of "goto cleanup_x" code. Go coroutines (goroutines) are functions invoked with the "go" keyword. These cannot be stopped or resumed, but might be (possibly) executed on a different thread. In any case, they are not guaranteed to be executed immediately in the normal flow of the code.
- coldtea 9y ago>Ehm, not sure I understood, but I'd say no. Defer is just code that is executed in reverse order upon return from a fuction. I'd say more like the equivalent of a "finally" clause (or more) for your whole function. Though not sure about the "executed in reverse order part" -- what's "in reverse order" about Defer? Except if you mean that multiple defers get executed "last seen first"...
- 19eightyfour 9y agoThanks alot for explaining, I think i get it a bit better now.