網站首頁 編程語言 正文
可以用作一些資源的釋放。
1.在一個函數內的defer執行順序是先寫的后執行,后寫的先執行(遵循棧結構)
func DeferTest1(){ defer fmt.Println("我是 defer1") defer fmt.Println("我是 defer2") fmt.Println("我是DeferTest1") fmt.Println("我是DeferTest2") }
結果:
我是DeferTest1
我是DeferTest2
我是 defer2
我是 defer1
2.defer 執行語句的值和定義defer語句函數的關系
func DeferTest2(){ i:= 0 defer fmt.Printf("defer i=%d\t",i) for ;i<=10;i++{ fmt.Printf("i=%d\t",i) } fmt.Println() }
執行結果
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10 ??
defer i=0
3.defer的原理
首先看下defer和return語句的區別,如下
可以看到 return 執行的時候 將結果x賦值給了返回值,然后執行了RET指令,而defer語句執行的時候,是在RET指令之前。所以這里注意一下。返回值和x的關系。如果x是一個值類型,這里是進行了拷貝的。可以看下下面幾個例子:
①
func defer1() int { x := 1 defer func() { x++<br data-filtered="filtered"> }() return x }
②
func defer2() (x int) { defer func() { x++ }() return 1 }
③
func defer3() (y int) { x := 1 defer func() { x++ }() return x }
④
func defer4() (x int) { defer func(x int) { x++ }(x) return 1 }
分別打印這幾個方法的結果,返回值分別如下:
defer1: 1
defer2: 2
defer3: 1
defer4: 1
根據上面圖上的解釋:
- ①defer執行之前,將x賦值給了返回值(這是一個值拷貝),然后修改x的值,對返回值是無影響的,所以返回的是1
- ②返回值的名稱就是x,此時defer執行前把x賦值為1,然后defer修改x的值, x被增加,故返回的是2
- ③返回值名稱是y,defer執行前,y被賦值為1,defer執行修改x對y無影響,返回也是1
- ④返回值名稱雖然是x,但是defer執行的func是一個帶參數的函數,此時傳入的參數x是一個值拷貝,作用域是內部,對于外部的x無影響,所以返回的也是1
原文鏈接:https://www.cnblogs.com/dcz2015/p/11102226.html
相關推薦
- 2022-08-20 python?tkinter庫的Text記錄點擊路經和刪除記錄詳情_python
- 2022-07-24 Python實現FIFO緩存置換算法_python
- 2022-05-10 開發跨域問題的解決
- 2022-04-06 .NET?Core使用CZGL.SystemInfo庫獲取主機運行資源_基礎應用
- 2022-08-17 C++詳細分析lambda表達式的本質_C 語言
- 2024-01-05 使用idea構建父子類springboot項目教程
- 2022-03-16 react實現todolist的增刪改查詳解_React
- 2022-07-26 Python文件處理、os模塊、glob模塊_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支