defer func running timing

153 views
Skip to first unread message

Lee Chou

unread,
Jun 25, 2022, 4:41:11 PM6/25/22
to golang-nuts
Hello,

https://go.dev/play/p/J1tVplkIrjt  

why o1.Ref print `2` but p1.Ref print `1` ? 
why o1.Ref print `2` but o2.NonRef print `3` ? it's so confused.

Sean Liao

unread,
Jun 25, 2022, 5:11:29 PM6/25/22
to golang-nuts
Maybe it's clearer if you look at what's happening like this https://go.dev/play/p/jAia9OPJfbY

The arguments to defer are evaluated immediately, but the execution only happens later

- sean

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/19cbb40a-b21a-4dd5-964d-7921095de33dn%40googlegroups.com.

Lee Chou

unread,
Jun 26, 2022, 4:12:22 AM6/26/22
to golang-nuts
Thanks for taking time. It's really big help. I understand what exactly happened.

best regards

- lee

Suresh Tupakula

unread,
Jun 27, 2022, 1:03:59 AM6/27/22
to Lee Chou, golang-nuts
Hi Lee, 

  All the defer functions are pushed into stack. When unwinding the stack , the last  function pushed comes out first and hence you see the execution order is reversed

--
Reply all
Reply to author
Forward
0 new messages