1. 程式人生 > >Golang 中 defer 小坑

Golang 中 defer 小坑

package main

import (
	"fmt"
)

func main() {
	x, y := 1, 2

	defer fmt.Println("defer", x, y)

	defer func() {
		fmt.Println("defer func", x, y)
	}()

	defer func(x int) {
		fmt.Println("defer func(x)", x, y)
	}(x)

	x *= 10
	y *= 20

	fmt.Println(x, y)
}

結果為:

10 40
defer func(x) 1 40
defer func 10 40
defer 1 2