Go defer sentence

package main

import "fmt"

func f1() int {
	// 1, perform return value is assigned, the return value is equal to x, is equal to 5
	// 2, defer the implementation of the statement, x ++, x is equal to 6
	// 3, the return instruction, 5 Return value
	x := 5
	defer func() {
		x ++ // modification is x, instead of returning value
	}()
	return x
}

func f2() (x int) {
	// 1, the first implementation of the return value assignment, so return 5 -> x = 5
	// 2, defer statement executed, returns the value x ++ -> x = 6
	// 3, the return instruction to return 6
	defer func() {
		x++
	}()
	return 5
}

func f3() (y int) {
	x := 5
	defer func(x int) {
		x++
	}(x)
	return x
}

func f4() (x int) {
	defer func(x int) {
		x ++ // copy function is changed, and the outer layer does not affect the value of x
	}(x)
	return 5 
}

func main() {
	fmt.Println(f1())
	fmt.Println(f2())
	fmt.Println(f3())
	fmt.Println(f4())
}

 

Guess you like

Origin www.cnblogs.com/noonjuan/p/11688925.html