현재 3권의 신간들인 Go Optimizations 101, Go Details & Tips 101Go Generics 101이 출간되어 있습니다. Leanpub 서점에서 번들을 모두 구입하시는 방법이 비용 대비 효율이 가장 좋습니다.

Go에 대한 많은 정보들과 Go 101 책들의 최신 소식을 얻으시려면 Go 101 트위터 계정인 @Go100and1을 팔로잉 해주세요.

More about Deferred Function Calls

Deferred function calls have been introduced before. Due to the limited Go 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 (at least for Go 1.20), except the calls to the built-in copy and recover functions. On the other hand, 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 in practice. As far as I know, only the calls to the built-in append function may needed to be deferred 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 (value) in a deferred function call is evaluated when the call is pushed into the deferred call queue of the current goroutine. For example, the following program will print false.
package main

import "fmt"

func main() {
	var f = func () {
		fmt.Println(false)
	}
	defer f()
	f = func () {
		fmt.Println(true)
	}
}

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

import "fmt"

func main() {
	defer fmt.Println("reachable 1")
	var f func() // f is nil by default
	defer f()    // panic here
	// The following lines are also reachable.
	fmt.Println("reachable 2")
	f = func() {} // useless to avoid panicking
}

The Evaluation Moment of Receiver Arguments of Deferred Method Calls

As explained before, the arguments of a deferred function call are also evaluated when the deferred call is pushed into the deferred call queue of the current goroutine.

Method receiver arguments are also not exceptions. For example, the following program prints 1342.
package main

type T int

func (t T) M(n int) T {
  print(n)
  return t
}

func main() {
	var t T
	// "t.M(1)" is the receiver argument of the method
	// call ".M(2)", so it is evaluated when the
	// ".M(2)" call is pushed into deferred call queue.
	defer t.M(1).M(2)
	t.M(3).M(4)
}

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, for there are so many f.Close() calls in the function without deferred calls that it has a higher possibility to miss one of them.

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 without unlocking the Mutex value. 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. For the official Go compiler, before version 1.13, deferred function calls will cause a few performance losses at run time. Since Go Toolchain 1.13, some common defer use cases have got optimized much, so that generally we don't need to care about the performance loss problem caused by deferred calls. Thank Dan Scales for making the great optimizations.

Kind-of Resource Leaking by Deferring Function Calls

A very large deferred call queue may also consume much memory, and some resources might not get released in time if some calls are delayed too much. 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 before the function exits.
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 improved 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
			}
			// The close method will be called at
			// the end of the current loop step.
			defer f.Close()

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

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

	return nil
}


Index↡

The Go 101 프로젝트는 Github 에서 호스팅됩니다. 오타, 문법 오류, 부정확한 표현, 설명 결함, 코드 버그, 끊어진 링크와 같은 모든 종류의 실수에 대한 수정 사항을 제출하여 Go 101을 개선을 돕는 것은 언제나 환영합니다.

주기적으로 Go에 대한 깊이 있는 정보를 얻고 싶다면 Go 101의 공식 트위터 계정인 @go100and1을 팔로우하거나 Go 101 슬랙 채널에j가입해주세요.

이 책의 디지털 버전은 아래와 같은 곳을 통해서 구매할 수 있습니다.
Go 101의 저자인 Tapir는 2016년 7월부터 Go 101 시리즈 책들을 집필하고 go101.org 웹사이트를 유지 관리하고 있습니다. 새로운 콘텐츠는 책과 웹사이트에 수시로 추가될 예정입니다. Tapir는 인디 게임 개발자이기도 합니다. Tapir의 게임을 플레이하여 Go 101을 지원할 수도 있습니다. (안드로이드와 아이폰/아이패드용):
  • Color Infection (★★★★★), 140개 이상의 단계로 이루어진 물리 기반의 캐주얼 퍼즐 게임
  • Rectangle Pushers (★★★★★), 2가지 모드와 104개 이상의 단계로 이루어진 캐주얼 퍼즐 게임
  • Let's Play With Particles, 세가지 미니 게임이 있는 캐주얼 액션 게임
페이팔을 통한 개인 기부도 환영합니다.

색인: