defer

不管程序是否出现异常,均在函数退出时候,自动执行相关代码

实战

实例1
package main

import (
	"fmt"
)

func main() {
	defer func() {
		fmt.Println("main defer")
	}()

	if err := test0(); err != nil {
		fmt.Println(err.Error())
		return
	}

	if err := test1(); err != nil {
		fmt.Println(err.Error())
		return
	}
}

func test0() error {
	return nil
}

func test1() error {
	return nil
}

运行结果

	main defer
实例2
package main

import (
	"fmt"
	"errors"
)

func main() {
	defer func() {
		fmt.Println("main defer")
	}()

	if err := test0(); err != nil {
		fmt.Println(err.Error())
		return
	}

	if err := test1(); err != nil {
		fmt.Println(err.Error())
		return
	}
}

func test0() error {
	return errors.New("test0 error") 
}

func test1() error {
	return nil
}

运行结果

test0 error
main defer
实例3
package main

import (
	"fmt"
	"errors"
)

func main() {
	defer func() {
		fmt.Println("main defer")
	}()

	if err := test0(); err != nil {
		fmt.Println(err.Error())
		return
	}

	if err := test1(); err != nil {
		fmt.Println(err.Error())
		return
	}
}

func test0() error {
	return nil
}

func test1() error {
	return errors.New("test1 error") 
}

运行结果

test1 error
main defer

实例4

package main

import (
	"fmt"
	"errors"
)

func main() {
	defer func() {
		fmt.Println("main defer0")
	}()

	defer func() {
		fmt.Println("main defer1")
	}()

	if err := test0(); err != nil {
		fmt.Println(err.Error())
		return
	}

	if err := test1(); err != nil {
		fmt.Println(err.Error())
		return
	}
}

func test0() error {
	defer func() {
		fmt.Println("test0 defer")
	}()
	return nil
}

func test1() error {
	defer func() {
		fmt.Println("test1 defer")
	}()
	return errors.New("test1 error") 
}

运行结果

test0 defer
test1 defer
test1 error
main defer1
main defer0