golang defer语句简单解析

栏目: Go · 发布时间: 6年前

内容简介:下面举例说明了defer语句的作用:输出结果:很明显 defer语句的执行顺序是反的。这种语法给我们的资源关闭提供了很好的帮助。

defer

下面举例说明了defer语句的作用:

package main

import "fmt"

func main() {

    i := 10
    defer incr(i)
    defer incr2(i)
    defer incr3(i)

}

func incr(i int){
    j := i -1
    fmt.Println(j)
}

func incr2(i int){
    j := i -2
    fmt.Println(j)
}

func incr3(i int){
    j := i -3
    fmt.Println(j)
}

输出结果:

GOROOT=C:\Go #gosetup
GOPATH=C:\Users\DELL\go #gosetup
C:\Go\bin\go.exe build -o C:\Users\DELL\AppData\Local\Temp\___go_build_cmpl_go.exe C:/Users/DELL/ActiveGo/src/spider/main/cmpl.go #gosetup
"C:\Program Files\JetBrains\GoLand 2018.3.2\bin\runnerw64.exe" C:\Users\DELL\AppData\Local\Temp\___go_build_cmpl_go.exe #gosetup
7
8
9

Process finished with exit code 0

很明显 defer语句的执行顺序是反的。这种语法给我们的资源关闭提供了很好的帮助。

比如流的关闭啊,文件的关闭啊等等。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Haskell

Haskell

Simon Thompson / Addison-Wesley / 1999-3-16 / GBP 40.99

The second edition of Haskell: The Craft of Functional Programming is essential reading for beginners to functional programming and newcomers to the Haskell programming language. The emphasis is on th......一起来看看 《Haskell》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具