3 ms·
Is that actually returning err as the deferred return value of test? In other words, to the caller of test it appears test returns the result of the deferred?
by 19eightyfour 9y ago
Is that actually returning err as the deferred return value of test? In other words, to the caller of test it appears test returns the result of the deferred?
- dullgiulio 9y agoDeferred functions don't return anything. You can modify the values that are returned by the parent function, and those will be returned as the deferred function modified them.
- fpoling 9y agoYep, and one cannot simulate that with local variables. In Go "return v" copies v into the return location before calling the deferred code. If that location is not named, the deferred function has no way to change it, see https://play.golang.org/p/Opg4XI08P7 https://play.golang.org/p/Opg4XI08P7
- 19eightyfour 9y agoI got it. That's a neat example. Do you have to define that deferred function inside the caller, in order to reference the name? Or can you factor out deferred functions to be used by various callers and pass in the return names for them to modify?
- fpoling 9y agoYou can pass a pointer to the named return values to a function defined outside, like in https://play.golang.org/p/5jBKcUCj8C https://play.golang.org/p/5jBKcUCj8C .
- 19eightyfour 9y agoAh, okay, thanks. I get it better now. Sort of like decorators in purpose, then.