Two type of defer print with different result

Hello, I am a beginner in Golang, and I have discovered that using these two kinds of defer statements can yield different results. Here is my code.

call 1

func TestDefer(t *testing.T) {
	var test string
	defer t.Log(test)
	test = "hello"
}

call 2

func TestDefer(t *testing.T) {
	var test string
	defer func() {
		t.Log(test)
	}()
	test = "hello"
}

Can someone please explain the reason behind this difference?

Here’s your answer:

… and from the docs:

Each time a “defer” statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

So by adding a layer of indirection in the second example, only the outer function is evaluated at the time you add it to the stack (not the call to t.Log). As a new gopher, it’s good to be careful/deliberate about defer statements (along with similar gotchas in goroutines!).

2 Likes

Thank you

when deferred function is a closure, the t.Log() arguments are not evaluated until the closure is executed,

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.