Explain the execution order of defer statements and when exactly a deferred function executes relative to the return values of the surrounding function.

Last updated 20 June 2026

  • Deferred calls run in LIFO order (last registered runs first), and their arguments are evaluated when the defer statement executes, not when the call runs.

  • On return x, the return value is set first, then deferred functions run, then control goes back to the caller.

  • So with named return values a deferred function can modify the result (e.g. return 5 plus a deferred result++ yields 6), commonly used to set errors in recover.

  • https://www.reddit.com/r/rust/comments/1h15md8/goodbye_rust_i_wish_you_success_but_im_back_to_c/
  • https://www.reddit.com/r/golang/comments/1gfjnzm/since_when_is_senior_golang_developer_expected_to/
All Golang interview questions