Skip to content

Instantly share code, notes, and snippets.

@devrim
Created July 15, 2012 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devrim/3118634 to your computer and use it in GitHub Desktop.
Save devrim/3118634 to your computer and use it in GitHub Desktop.
go defer func
package main
import (
"fmt"
)
func f() (ret int) {
defer func() {
ret++
}()
return 1
}
func main() {
fmt.Println(f())
}
@devrim
Copy link
Author

devrim commented Jul 15, 2012

This prints 2.
Problem: if defer() runs after 1 is returned, changing ret var after return 1 is returned, main() should print 1..

@fpsiorz
Copy link

fpsiorz commented Jun 25, 2013

return doesn't actually return a value, it just ends the function's regular execution and sets the return values. those values can still be changed by a deferred function call, as your code demonstrates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment