肾虚对男生意味着什么| 9月25是什么星座| 七月有什么节| 阿司匹林是什么药| 树叶又什么又什么| 什么食物对肝有好处| 吉祥如意是什么意思| 王加呈念什么| 妈妈最大的愿望是什么| 什么情况下需要割包皮| 肌酐是什么指标| 红花油和活络油有什么区别| 淋巴发炎吃什么药| 大学没毕业算什么学历| 青蛙像什么| 什么是肠梗阻| 内向什么意思| 阻断是什么意思| 补铁有什么好处| 贵州有什么山| 为什么老流鼻血| 左脸长痘是什么原因| 消字号是什么意思| 高血压吃什么药最好| 婴儿头发竖起来是什么原因| 医生为什么穿白大褂| 肾阴虚吃什么| 89年的属什么| 沙和尚是什么妖怪| 钠对人体有什么作用| 黄鼻涕是什么感冒| 肾结石什么不可以吃| 孕妇不能吃什么| 孕妇适合喝什么茶| 什么药治痒效果最好| 洛索洛芬钠片和布洛芬有什么区别| 四级什么时候报名| 难过美人关是什么生肖| 鼻炎吃什么药效果最好| 土克水是什么意思| 减肥期间可以吃什么零食| 减肥吃什么食物瘦得快| 气血不足吃什么食物| 孕妇吃海带有什么好处| 痛苦的反义词是什么| 南瓜炒什么好吃| 有酒瘾是什么感觉| 什么是绿茶| 生理盐水有什么作用| 火影忍者大结局是什么| 5月是什么星座| 梦到门牙掉了是什么意思| 什么发育成种皮| 前列腺炎吃什么药| 江米和糯米有什么区别| d是什么元素| 生辉是什么意思| 髻是什么意思| 下午5点半是什么时辰| b型o型生出来的孩子什么血型| 什么鱼清蒸好吃| 陈醋和白醋有什么区别| 吃枸杞对身体有什么好处| 组cp是什么意思| 皮粉色是什么颜色| 长期喝什么茶能降三高| 桃符指的是什么| 婶婶是什么意思| 224是什么星座| 83年属猪是什么命| 吃什么有助于伤口愈合| 眼角膜脱落什么症状| 抵抗力差吃什么可以增强抵抗力| 看病人送什么花合适| 牙龈肿痛吃什么中成药| 家里为什么会有蟑螂| 七叶一枝花主治什么病| 西瓜什么季节成熟| 生孩子送什么| 脚酸臭是什么原因| 慢性荨麻疹是什么症状| 应接不暇的暇是什么意思| 失信是什么意思| 印字五行属什么| 支原体阳性是什么意思| 中医调理身体挂什么科| 不耐受和过敏有什么区别| 寂寞什么意思| 口腔医学技术是干什么的| 羟基维生素d是什么| 小狗得细小是什么症状| 猫不能吃什么| 针眼用什么眼药水| 小肠换气什么症状| 电销是什么| 钓鲈鱼用什么饵最好| ls是什么牌子| 辰时是什么时候| mdr是什么意思| 肾小球滤过率是什么意思| 嫖娼是什么意思| 绘本是什么意思| 为什么会心梗| 什么大| 与虎谋皮什么意思| 八月一日是什么日子| 曹休和曹操什么关系| 口臭舌苔白厚吃什么药| 舌头开裂是什么原因| 吃脆骨有什么好处| 为什么叫关东军| 开宠物医院需要什么条件| 泡是什么意思| 容易上火是什么原因| 次长是什么职位| 仁德是什么意思| 什么是uv| 周杰伦什么星座| 吗丁啉有什么功效| 非那根又叫什么| 梦见蜜蜂是什么预兆| 来月经喝什么好| 二月二十五号是什么星座| 一天中什么时候最冷| 眼结石是什么原因引起的| 什么寒什么冻| 单身领养孩子需要什么条件| ac什么意思| 阴茎破皮擦什么药| 降火祛痘喝什么茶| 破伤风是什么意思| 淋巴结影是什么意思| 坐地能吸土是什么意思| 高铁座位为什么没有e| 脑梗吃什么药好| 小苏打学名叫什么| 胰尾显示不清什么意思| 三月份是什么星座的| 霍建华为什么娶林心如| 为什么会有血管瘤| 火车票改签是什么意思| 720是什么意思| 首选是什么意思| 尿道炎什么症状| 南瓜皮可以吃吗有什么作用| 减肥最快的运动是什么运动| 牛郎织女是什么意思| 吃什么润肺| 海鲜和什么不能一起吃| 舌根发麻是什么原因| 肺气肿什么症状| 严重失眠吃什么药最好| 土是什么颜色| 寒包火感冒吃什么药| 怀孕前三个月需要注意什么| 一个田一个比念什么| 凌晨两点半是什么时辰| 2019年属什么生肖| 羊水穿刺是检查什么| 炸东西用什么油| 馥字五行属什么| 知了猴什么时候出来| 割包皮看什么科| 脚气泡脚用什么泡最好| 1981年属什么生肖| 新车上牌需要什么资料| 恋爱观是什么| 什么散步填词语| 前列腺增大伴钙化是什么意思| 光脚走路有什么好处| 月经不规律吃什么药调理| 透析是什么意思啊| eso是什么意思| 身上长小红痣是什么原因| 介石是什么意思| 送爸爸什么礼物最实用| 精湛是什么意思| 地图舌吃什么药| 什么方法可以快速入睡| 嬴稷是秦始皇的什么人| 骨折一个月能恢复到什么程度| 入心是什么意思| 幽门螺旋杆菌吃什么药最好| 大专有什么专业| 小孩呕吐是什么原因引起的| 为什么手上会起小水泡| 散粉是干什么用的| 脂肪浸润是什么意思| 猫离家出走预示着什么| 痔疮为什么不建议手术| 哥哥的孩子叫我什么| 肝肾阴虚吃什么中成药| 支原体衣原体是什么病| 李世民和武则天什么关系| 头皮脂溢性皮炎用什么药| 心衰竭是什么症状| 半夜会醒是什么原因| 什么是甲减| 什么是粘胶纤维| 胆囊壁毛糙吃什么药效果好| 耳石症是什么症状| 女性尿臭味重是什么病| 节肢动物用什么呼吸| 打嗝多是什么原因| 嗓子疼吃什么药见效最快| 每天吃鸡蛋有什么好处和坏处| 象是什么结构的字| 生完孩子可以吃什么水果| 如来是什么意思| 宫商角徵羽是什么意思| 什么花在什么时间开| 虚岁31岁属什么生肖| 小孩咬手指甲是什么原因| 珅是什么意思| 有样学样是什么意思| 护士是干什么的| 学考成绩什么时候公布| 腺是什么意思| 鸭子什么意思| 9月17日是什么星座| 为什么老是犯困想睡觉| 视力模糊用什么眼药水| 煮奶茶用什么茶叶| 中耳炎有什么症状| 中国最好的大学是什么大学| 梦见大蛇是什么意思| 为什么会莫名其妙的哭| 疱疹是什么原因长的| 泡打粉可以用什么代替| apgar评分是什么意思| perry是什么意思| 7月27日什么星座| sdh是什么意思| 孕妇吃什么坚果比较好| 右耳朵耳鸣是什么原因| 元旦吃什么| 肺结核吃什么药| eu是什么元素| 铁瓷是什么意思| 男怕穿靴女怕戴帽什么意思| 石斛能治什么病| 葛根粉吃了有什么好处| 发来贺电是什么意思| 成都有什么大学| 苹果有什么功效和营养| 立是什么结构的字| 肚子疼恶心想吐吃什么药| 白蚁吃什么| 什么叫信仰| 北海有什么好玩的| 什么人不能吃狗肉| 南京为什么叫金陵| 梦见吃红薯是什么意思| 脚常抽筋是什么原因| 1941年是什么年| 玛卡是什么| 女孩为什么难得午时贵| 看脖子应该挂什么科| 虾片是什么做的| honey什么意思| cooh是什么基| 六月十五号是什么星座| 降龙十八掌最后一掌叫什么| 什么是豆制品| 百度
Table of Contents
Feature 1: Calling order when multiple defers are used: first in, last out
Feature 3: Function parameters after defer are confirmed at the time of declaration (precalculated parameters) " >Feature 3: Function parameters after defer are confirmed at the time of declaration (precalculated parameters)
Run demo4_1, you can find that defer and return are executed at the end of the function, but return is executed before defer;
Run demo5_1, you can see that when panic occurs, Trigger the declared defer to pop out of the stack and then panic. However, the defer declared after the panic will not be executed.
Full code:
Home Backend Development Golang Use eight demos to understand the five major features of Go language defer

富屋贫人是什么意思

Apr 23, 2023 pm 05:40 PM
go language

百度   早在3月7日,大众汽车(中国)销售有限公司就曾向国家质检总局备案的召回计划,表示公司将自2018年4月30日起,召回2014年12月21日至2017年11月12日期间生产的部分进口2015-2018年款途锐系列汽车。

Using the defer keyword in Go language can delay code execution until the end of the function. In development, we often use the defer keyword to complete the aftermath work, such as closing open file descriptors, closing connections, and releasing resources.

func?demo0()?{
????fileName?:=?"./test.txt"
????f,?_?:=?os.OpenFile(fileName,?os.O_RDONLY,?0)
????defer?f.Close()

????contents,?_?:=?ioutil.ReadAll(f)
????fmt.Println(string(contents))}

deferThe keyword usually follows immediately after the resource opening code to prevent subsequent forgetting to release the resource. The code declared by defer will not actually be executed until the end of the function. Although defer is simple and easy to use, but if you ignore its features, you will face confusion during development . Therefore, I summarized the five major features of defer and gradually introduced the features of defer through 8 demos.

Feature 1: Calling order when multiple defers are used: first in, last out

When multiple defer keywords are used, the defer statement declared first is called later. Similar to the "stack" first-in-last-out feature, this feature of defer is also easy to understand. Resources opened by first may be relied upon by subsequent code, so ## It is safe to release after #.

func?demo1()?{
????for?i?:=?0;?i?<?5;?i++?{
????????defer?fmt.Println("defer:",?i)
????}}//?defer:?4//?defer:?3//?defer:?2//?defer:?1//?defer:?0
Feature 2: The scope is the current function, and there are different defer stacks under different functions

Run demo2. It can be seen from the results that the first anonymous function and the second anonymous function The order of defer execution of functions does not matter.

The defer scope is only the current function and is executed at the end of the current function, so there are different defer stacks under different functions.

func?demo2()?{
????func()?{
????????defer?fmt.Println(1)
????????defer?fmt.Println(2)
????}()

????fmt.Println("===?新生代农民工啊?===")

????func()?{
????????defer?fmt.Println("a")
????????defer?fmt.Println("b")
????}()}//?2//?1//?===?新生代农民工啊?===//?b//?a
Run demo3_1, according to the results, we can conclude: defer in

The value of the formal parameter n has been confirmed when is declared, not when is executed; therefore, no matter how the subsequent variable num changes, it will not affect the output result of defer.

func?demo3_1()?{
????num?:=?0
????defer?func(n?int)?{
????????fmt.Println("defer:",?n)
????}(num)
????//?等同?defer?fmt.Println("defer:",?num)

????for?i?:=?0;?i?<?10;?i++?{
????????num++
????}

????fmt.Println(num)}//10//defer:?0
Run demo3_2, why is the final output result of defer here the same as the variable num? Because pointers are used here.

defer
When declaring, the address pointed by the formal parameter p pointer has been confirmed, pointing to the variable num; subsequently the variable num changes. So when defer is executed, the output is the current value of the variable num pointed to by the p pointer.

func?demo3_2()?{
????num?:=?0
????p?:=?&num????defer?func(p?*int)?{
????????fmt.Println("defer:",?*p)
????}(p)

????for?i?:=?0;?i?<?10;?i++?{
????????num++
????}

????fmt.Println(*p)}//10//defer:?10
Look at demo3_3 again. The variables printed by defer are not passed in through function parameters. The "global variable" num is only obtained when defer

is executed, so the output result of defer is the same as the variable. num is consistent.

func?demo3_3()?{
????num?:=?0
????defer?func()?{
????????fmt.Println("defer:",?num)
????}()

????for?i?:=?0;?i?<?10;?i++?{
????????num++
????}

????fmt.Println(num)}//10//defer:?10
Feature 4: return and defer execution order: return first defer then

Run demo4_1, you can find that defer and return are executed at the end of the function, but return is executed before defer;

func?demo4_1()?(int,?error)?{
????defer?fmt.Println("defer")
????return?fmt.Println("return")}//?return//?defer

This is obvious from the output results

, but when the execution order of return and defer and the

**function return value** "meet", Many complex scenarios will result. In demo4_2, the function uses to name the return value
, and the final output result is 7. It has gone through the following processes:

    (First) the variable num is used as the return value, and the initial value is 0;
  1. (Second) Then The variable num is assigned a value of 10;
  2. (Then) when return, the variable num is reassigned a value of 2 as the return value;

  3. (Then) defer is executed after return, and the variable num is obtained for modification, and the value is 7;
  4. (Finally) the variable num is used as the return value, and the final function return result is 7;
  5. func?demo4_2()?(num?int)?{
    ?num?=?10
    ?defer?func()?{
    ?????num?+=?5
    ?}()
    
    ?return?2}//?7

  6. Let’s look at another example.
In demo4_3, the function uses

anonymous return value
, and the final result output is 2. The process is as follows:

    Enters the function, and the return value variable is not created at this time;
  1. creates the variable num and assigns the value to 10; When
  2. return, create a function return value variable and assign it a value of 2; you can regard this return value variable as an anonymous variable, or as a, b, c, or d variable ..., but it is not the variable num;
  3. defer, no matter how you modify the variable num, it has nothing to do with the function return value;
  4. Therefore, the final function return result is 2;
  5. func?demo4_3()?int?{
    ?num?:=?10
    ?defer?func()?{
    ?????num?+=?5
    ?}()
    
    ?return?2}//?2

    Feature 5: When panic occurs, the declared defer will pop out of the stack and execute

    Run demo5_1, you can see that when panic occurs, Trigger the declared defer to pop out of the stack and then panic. However, the defer declared after the panic will not be executed.

    func?demo5_1()?{
    ?defer?fmt.Println(1)
    ?defer?fmt.Println(2)
    ?defer?fmt.Println(3)
    
    ?panic("没点赞异常")?//?触发defer出栈执行
    
    ?defer?fmt.Println(4)?//?得不到执行}

    It is precisely by using this feature that panic can be captured through recover in defer to prevent the program from crashing.

    func?demo5_2()?{
    ?defer?func()?{
    ?????if?err?:=?recover();?err?!=?nil?{
    ?????????fmt.Println(err,?"问题不大")
    ?????}
    ?}()
    
    ?panic("没点赞异常")?//?触发defer出栈执行
    
    ?//?...}

    Attached

    Full code:

    github.com/newbugcoder/learngo/tre...

The above is the detailed content of Use eight demos to understand the five major features of Go language defer. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Do I need to install an Oracle client when connecting to an Oracle database using Go? Do I need to install an Oracle client when connecting to an Oracle database using Go? Apr 02, 2025 pm 03:48 PM

Do I need to install an Oracle client when connecting to an Oracle database using Go? When developing in Go, connecting to Oracle databases is a common requirement...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

centos postgresql resource monitoring centos postgresql resource monitoring Apr 14, 2025 pm 05:57 PM

Detailed explanation of PostgreSQL database resource monitoring scheme under CentOS system This article introduces a variety of methods to monitor PostgreSQL database resources on CentOS system, helping you to discover and solve potential performance problems in a timely manner. 1. Use PostgreSQL built-in tools and views PostgreSQL comes with rich tools and views, which can be directly used for performance and status monitoring: pg_stat_activity: View the currently active connection and query information. pg_stat_statements: Collect SQL statement statistics and analyze query performance bottlenecks. pg_stat_database: provides database-level statistics, such as transaction count, cache hit

Is the Go language interface a duck type? What is the implementation mechanism of polymorphism? Is the Go language interface a duck type? What is the implementation mechanism of polymorphism? Apr 02, 2025 pm 02:48 PM

Interfaces and polymorphism in Go: Clarifying common misunderstandings Many Go beginners often connect the concepts of "duck type" and "polymorphism" with Go...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles
幺妹是什么意思 劳损是什么意思 8宫代表什么 温水煮青蛙什么意思 美人坯子是什么意思
凌晨6点是什么时辰 32岁属什么 体测是什么意思 势不可挡是什么意思 发热挂什么科
血流信号是什么意思 什么叫腔梗 四季不安痣是什么意思 晦气是什么意思 2月18号是什么星座
手上的线分别代表什么图解 角加斗念什么 鹿晗什么时候回国的 霉菌性阴道炎什么症状 系带割掉了有什么影响
中指戴戒指什么意思hcv9jop1ns1r.cn 6月15是什么星座hcv9jop0ns4r.cn 着了过是什么词hcv7jop5ns3r.cn 小手指麻木是什么原因hcv8jop1ns6r.cn 婆媳关系为什么难相处hcv7jop5ns3r.cn
m3是什么意思bjhyzcsm.com 女人吃火龙果有什么好处aiwuzhiyu.com 吃茄子有什么好处和坏处hcv8jop1ns0r.cn 女人是男人的什么tiangongnft.com 脾大有什么危害hcv8jop9ns5r.cn
藜芦是什么hcv9jop1ns6r.cn 茹字五行属什么hcv8jop7ns5r.cn 心率过缓吃什么药hcv7jop5ns5r.cn 鸾凤是什么意思hcv8jop0ns1r.cn 嘴臭是什么原因hcv9jop0ns0r.cn
身上长肉疙瘩是什么原因hcv9jop4ns6r.cn 七杀大运是什么意思hcv8jop7ns9r.cn 碳酸钙是什么hcv9jop8ns2r.cn 老是头疼是什么原因hkuteam.com 咸鸭蛋不能和什么一起吃hcv8jop6ns1r.cn
百度