当前位置:网站首页>go defer

go defer

2022-04-23 20:43:00 baboon_ chen

One 、defer principle


 Insert picture description here

Two 、 Example

1、

package main

import (
	"fmt"
)

func funcA() int {
    
	x := 5
	defer func() {
    
		x += 1
	}()
	return x
}
func main() {
    
	fmt.Println(funcA())
}

/*  Output :5  reason : The return value in defer It was determined before  */

2、

func funcB() (x int) {
    
	defer func() {
    
		x += 1
	}()
	return 5
}

/*  Output :6  reason : First the 5 Assign a value to x, defer Call again x */

3、

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

/*  Output :5  reason : First the 5 Assign a value to y, defer Only change x */

4、

func funcD() (x int) {
    
	defer func(x int) {
    
		x += 1
	}(x)
	return 5
}

/*  Output :5  reason : First the 5 Assign a value to x, defer Call again x( Value passed ), What has changed is x Copy of  */

版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351196.html