Featured image of post Go Defer

Go Defer

如果在 defer 语句中或过程中(例如 defer wg.Wait())需要修改返回值,尽量使用命名返回值,以避免在代码维护和理解时出现混淆。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
)

func deferParam() (err error) {
	defer func() {
		err = fmt.Errorf("error")
	}()
	return err
}

func deferReturn() error {
	var err error
	defer func() {
		err = fmt.Errorf("error")
	}()
	return err
}

func main() {
	fmt.Println(deferParam())
	fmt.Println(deferReturn())
}
1
2
error
<nil>
Licensed under CC BY-NC-SA 4.0