More About Deferred Function Calls

Deferred function calls have been introduced before. Due to the limited knowledge at that time, some more details and use cases of deferred functions calls are not touched in that article. These details and use cases will be touched in the remaining of this article.

Calls To Many Built-in Functions With Return Results Can't Be Deferred

In Go, the result values of a call to custom functions can be all absent (discarded). However, for built-in functions with non-blank return result lists, the result values of their calls mustn't be absent (up to Go 1.11), except the calls to the built-in copy and recover functions. We have learned that the result values of a deferred function call must be discarded, so the calls to many built-in functions can't be deferred.

Fortunately, the needs to defer built-in function calls (with non-blank return result lists) are rare. As far as I know, only the calls to the built-in append function may be needed to defer sometimes. For this case, we can defer a call to an anonymous function which wraps the append call.
package main

import "fmt"

func main() {
	s := []string{"a", "b", "c", "d"}
	defer fmt.Println(s) // [a x y d]
	// defer append(s[:1], "x", "y") // error
	defer func() {
		_ = append(s[:1], "x", "y")
	}()
}

The Evaluation Moment Of Deferred Function Values

The called function in a deferred function call may be a nil function value. For such a case, the panic will occur before the deferred call is pushed into the deferred call stack of the current goroutine. An example:
package main

import "fmt"

func main() {
	defer fmt.Println("reachable")
	var f func() // f is nil by default
	defer f()    // panic here
	// The following lines are dead code.
	fmt.Println("not reachable")
	f = func() {}
}

The arguments of a deferred function call are also evaluated before the deferred call is pushed into the deferred call stack of the currrent goroutine.

Deferred Calls Make Code Cleaner And Less Bug Prone

Example:
import "os"

func withoutDefers(filepath string, head, body []byte) error {
	f, err := os.Open(filepath)
	if err != nil {
		return err
	}

	_, err = f.Seek(16, 0)
	if err != nil {
		f.Close()
		return err
	}

	_, err = f.Write(head)
	if err != nil {
		f.Close()
		return err
	}

	_, err = f.Write(body)
	if err != nil {
		f.Close()
		return err
	}

	err = f.Sync()
	f.Close()
	return err
}

func withDefers(filepath string, head, body []byte) error {
	f, err := os.Open(filepath)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = f.Seek(16, 0)
	if err != nil {
		return err
	}

	_, err = f.Write(head)
	if err != nil {
		return err
	}

	_, err = f.Write(body)
	if err != nil {
		return err
	}

	return f.Sync()
}

Which one looks cleaner? apparently, the one with the deferred calls, though a little. And it is less bug prone, what about if any of f.Close() calls in the other one is missed? ;)

The following is another example to show deferred calls can make code less bug prone. If the doSomething calls panic in the following example, the function f2 will exit by leaving the Mutex unlocked. So the function f1 is less bug prone.
var m sync.Mutex

func f1() {
	m.Lock()
	defer m.Unlock()
	doSomething()
}

func f2() {
	m.Lock()
	doSomething()
	m.Unlock()
}

Performance Losses Caused By Deferring Function Calls

It is not always good to use deferred function calls. Up to now (Go 1.11), for the official Go compiler, deferred function calls will cause some performance losses at run time, in particular for deferred function calls within loop code blocks.

For example, in the following example, the methods CounterB and IncreaseB are much more efficient than the methods CounterA and IncreaseA.
import "sync"

type T struct {
	mu sync.Mutex
	n  int64
}

func (t *T) CounterA() int64 {
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.n
}

func (t *T) CounterB() (count int64) {
	t.mu.Lock()
	count = t.n
	t.mu.Unlock()
	return
}

func (t *T) IncreaseA() {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.n++
}

func (t *T) IncreaseB() {
	t.mu.Lock()
	t.n++ // this line will not panic for sure
	t.mu.Unlock()
}

In the B-version functions, we should guarantee that the code between the Lock and Unlock calls will never panic.

Generally, the A-version functions are recommended to be used in practice. We should only adopt the B versions when we really care about the performance of the involved functions.

Kind-Of Resource Leaking By Deferring Function Calls

A very large deferred call stack may also consume much memory. The unexecuted deferred calls may prevent some resources from being released. For example, if there are many files needed to be handled in a call to the following function, then a large number of file handlers will be not get released in time.
func writeManyFiles(files []File) error {
	for _, file := range files {
		f, err := os.Open(file.path)
		if err != nil {
			return err
		}
		defer f.Close()

		_, err = f.WriteString(file.content)
		if err != nil {
			return err
		}

		err = f.Sync()
		if err != nil {
			return err
		}
	}

	return nil
}
For such cases, we can use an anonymous function to enclose the deferred calls so that the deferred function calls will get executed earlier. For example, the above function can be rewritten and optimized as
func writeManyFiles(files []File) error {
	for _, file := range files {
		if err := func() error {
			f, err := os.Open(file.path)
			if err != nil {
				return err
			}
			defer f.Close()

			_, err = f.WriteString(file.content)
			if err != nil {
				return err
			}

			return f.Sync()
		}(); err != nil {
			return err
		}
	}

	return nil
}


The Go 101 project is hosted on both Github and Gitlab. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

Support Go 101 by playing Tapir's games. Cryptocurrency donations are also welcome:
Bitcoin: 1xucQbv5jujFPPwhyg395ri5yV71hx9g9
Ethereum: 0x5dc4aa2c2bbfaadae373dadcfca11b3358912212